Skip to content

Commit

Permalink
feat: introduce cbtc example
Browse files Browse the repository at this point in the history
  • Loading branch information
Ludo Galabru committed Jun 7, 2022
1 parent cd622d3 commit e195f71
Show file tree
Hide file tree
Showing 19 changed files with 4,824 additions and 1 deletion.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@ npm-debug.log*
node-bindings/dist
node-bindings/build
**/settings/Mainnet.toml
**/settings/Testnet.toml
**/settings/Testnet.toml
examples/cbtc/backend/.build
vendor/orchestra-types-js/dist
6 changes: 6 additions & 0 deletions examples/cbtc/backend/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# package directories
node_modules
jspm_packages

# Serverless directories
.serverless
92 changes: 92 additions & 0 deletions examples/cbtc/backend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
<!--
title: 'AWS Simple HTTP Endpoint example in NodeJS'
description: 'This template demonstrates how to make a simple HTTP API with Node.js running on AWS Lambda and API Gateway using the Serverless Framework.'
layout: Doc
framework: v3
platform: AWS
language: nodeJS
authorLink: 'https://github.com/serverless'
authorName: 'Serverless, inc.'
authorAvatar: 'https://avatars1.githubusercontent.com/u/13742415?s=200&v=4'
-->

# Serverless Framework Node HTTP API on AWS

This template demonstrates how to make a simple HTTP API with Node.js running on AWS Lambda and API Gateway using the Serverless Framework.

This template does not include any kind of persistence (database). For more advanced examples, check out the [serverless/examples repository](https://github.com/serverless/examples/) which includes Typescript, Mongo, DynamoDB and other examples.

## Usage

### Deployment

```
$ serverless deploy
```

After deploying, you should see output similar to:

```bash
Deploying aws-node-http-api-project to stage dev (us-east-1)

✔ Service deployed to stack aws-node-http-api-project-dev (152s)

endpoint: GET - https://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/
functions:
hello: aws-node-http-api-project-dev-hello (1.9 kB)
```

_Note_: In current form, after deployment, your API is public and can be invoked by anyone. For production deployments, you might want to configure an authorizer. For details on how to do that, refer to [http event docs](https://www.serverless.com/framework/docs/providers/aws/events/apigateway/).

### Invocation

After successful deployment, you can call the created application via HTTP:

```bash
curl https://xxxxxxx.execute-api.us-east-1.amazonaws.com/
```

Which should result in response similar to the following (removed `input` content for brevity):

```json
{
"message": "Go Serverless v2.0! Your function executed successfully!",
"input": {
...
}
}
```

### Local development

You can invoke your function locally by using the following command:

```bash
serverless invoke local --function hello
```

Which should result in response similar to the following:

```
{
"statusCode": 200,
"body": "{\n \"message\": \"Go Serverless v3.0! Your function executed successfully!\",\n \"input\": \"\"\n}"
}
```


Alternatively, it is also possible to emulate API Gateway and Lambda locally by using `serverless-offline` plugin. In order to do that, execute the following command:

```bash
serverless plugin install -n serverless-offline
```

It will add the `serverless-offline` plugin to `devDependencies` in `package.json` file as well as will add it to `plugins` in `serverless.yml`.

After installation, you can start local emulation with:

```
serverless offline
```

To learn more about the capabilities of `serverless-offline`, please refer to its [GitHub repository](https://github.com/dherault/serverless-offline).
241 changes: 241 additions & 0 deletions examples/cbtc/backend/handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
import { BitcoinChainEvent, StacksChainEvent, StacksTransactionEventType, StacksFTBurnEventData } from "@hirosystems/orchestra-types";

import {
getNonce,
makeContractCall,
broadcastTransaction,
AnchorMode,
PostConditionMode,
addressFromHashMode,
AddressHashMode,
TransactionVersion,
standardPrincipalCVFromAddress,
uintCV,
addressToString,
} from '@stacks/transactions';
import { StacksTestnet } from '@stacks/network';
import { principalCV } from "@stacks/transactions/dist/clarity/types/principalCV";
const Script = require('bitcore-lib/lib/script');
const Opcode = require('bitcore-lib/lib/opcode');
const Networks = require('bitcore-lib/lib/networks');
const Transaction = require('bitcore-lib/lib/transaction');
const PrivateKey = require('bitcore-lib/lib/privatekey');
const Signature = require('bitcore-lib/lib/crypto/signature');
const { Output, Input } = require('bitcore-lib/lib/transaction');

interface HttpEvent {
routeKey: string,
body: string
authorization: string,
}

const cbtcAuthority = {
secretKey: "7287ba251d44a4d3fd9276c88ce34c5c52a038955511cccaf77e61068649c17801",
stxAddress: "ST1SJ3DTE5DN7X54YDH5D64R3BCB6A2AG2ZQ8YPD5",
btcAddress: "mr1iPkD9N3RJZZxXRk7xF9d36gffa6exNC",
}

const cbtcToken = {
contractAddress: "ST1PQHQKV0RJXZFY1DGX8MNSNYVE3VGZJSRTPGZGM",
contractName: "cbtc-token",
assetName: "cbtc"
}

const BITCOIN_NODE_URL = "http://localhost:18443";
const STACKS_NODE_URL = "http://localhost:20443";

module.exports.wrapBtc = async (event: HttpEvent) => {
let chainEvent: BitcoinChainEvent = JSON.parse(event.body);

// In this protocol, we're assuming that BTC transactions include 2 outputs:
// - 1 funding the authority address
// - 1 getting the change. p2pkh is being expected on this 2nd output
// that we're using for inferring the Stacks address to fund.
let satsAmount = chainEvent.apply[0].transaction.metadata.outputs[0].value;
let recipientPubkey = chainEvent.apply[0].transaction.metadata.outputs[1].script_pubkey;

// Build Stack address
let script = Script.fromBuffer(Buffer.from(recipientPubkey, "hex"));
let hashBytes = script.getPublicKeyHash().toString('hex');
let recipientAddress = addressFromHashMode(AddressHashMode.SerializeP2PKH, TransactionVersion.Testnet, hashBytes)

if (addressToString(recipientAddress) === cbtcAuthority.stxAddress) {
// Avoid minting when authority is unwrapping cBTC and keeping the change
return {
statusCode: 301,
}
}

// Build a Stacks transaction
const network = new StacksTestnet({ url: STACKS_NODE_URL });
const nonce = await getNonce(cbtcAuthority.stxAddress, network);
const txOptions = {
contractAddress: cbtcToken.contractAddress,
contractName: cbtcToken.contractName,
functionName: "mint",
functionArgs: [uintCV(satsAmount), standardPrincipalCVFromAddress(recipientAddress)],
fee: 1000,
nonce,
network,
anchorMode: AnchorMode.OnChainOnly,
postConditionMode: PostConditionMode.Allow,
senderKey: cbtcAuthority.secretKey
};
const tx = await makeContractCall(txOptions);

// Broadcast transaction to our Devnet stacks node
const result = await broadcastTransaction(tx, network)

return {
statusCode: 200,
body: JSON.stringify(
{
result: result,
},
null,
2
),
};
};

module.exports.unwrapBtc = async (event: HttpEvent) => {
let chainEvent: StacksChainEvent = JSON.parse(event.body);
let assetId = `${cbtcToken.contractAddress}.${cbtcToken.contractName}::${cbtcToken.assetName}`;
let transfer = undefined;

let receipt = chainEvent.apply[0].transaction.metadata.receipt;
for (let txEvent of receipt.events) {
if (txEvent.type === StacksTransactionEventType.StacksFTBurnEvent) {
let burnEvent = txEvent.data as StacksFTBurnEventData;
if (burnEvent.asset_identifier == assetId) {
transfer = { recipient: burnEvent.sender, amount: burnEvent.amount };
break
}
}
}

if (transfer === undefined) {
return {
message: 'Event not found',
statusCode: 404,
}
}
let response = await fetch(BITCOIN_NODE_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic '+btoa('devnet:devnet'),
},
body: JSON.stringify({
id: 0,
method: `listunspent`,
params: [1, 9999999, [cbtcAuthority.btcAddress]],
}),
});
let json = await response.json();
let unspentOutputs = json.result;

let recipientAddress = principalCV(transfer.recipient);
let authorityAddress = principalCV(cbtcAuthority.stxAddress);

let typicalSize = 600;
let txFee = 10 * typicalSize;
let totalRequired = parseInt(transfer.amount) + txFee;
let selectedUtxosIndices = [];
let cumulatedAmount = 0;
let i = 0;
for (let utxo of unspentOutputs) {
cumulatedAmount += utxo.amount * 100_000_000;
selectedUtxosIndices.push(i);
if (cumulatedAmount >= totalRequired) {
break;
}
i++;
}
if (cumulatedAmount < totalRequired) {
return {
message: 'Funding unsufficient',
unspentOutputs: unspentOutputs,
statusCode: 404,
}
}

selectedUtxosIndices.reverse();
let transaction = new Transaction();
transaction.setVersion(1);
let selectedUnspentOutput = [];
for (let index of selectedUtxosIndices) {
let unspentOutput = unspentOutputs[index];

unspentOutputs.splice(index, 1);
let input = Input.fromObject({
prevTxId: unspentOutput.txid,
script: Script.empty(),
outputIndex: unspentOutput.vout,
output: new Output({
satoshis: parseInt(transfer.amount),
script: Buffer.from(unspentOutput.scriptPubKey, 'hex'),
})
});
transaction.addInput(new Input.PublicKeyHash(input));
selectedUnspentOutput.push(unspentOutput);
}

let unwrapOutput = new Output({
satoshis: parseInt(transfer.amount),
script: new Script()
.add(Opcode.map.OP_DUP)
.add(Opcode.map.OP_HASH160)
.add(Buffer.from(recipientAddress.address.hash160, 'hex'))
.add(Opcode.map.OP_EQUALVERIFY)
.add(Opcode.map.OP_CHECKSIG)
});

transaction.outputs.push(unwrapOutput);

let changeOutput = new Output({
satoshis: cumulatedAmount - parseInt(transfer.amount) - txFee,
script: new Script()
.add(Opcode.map.OP_DUP)
.add(Opcode.map.OP_HASH160)
.add(Buffer.from(authorityAddress.address.hash160, 'hex'))
.add(Opcode.map.OP_EQUALVERIFY)
.add(Opcode.map.OP_CHECKSIG)
});

transaction.outputs.push(changeOutput);

let secretKey = new PrivateKey(
cbtcAuthority.secretKey.slice(0, 64),
Networks.testnet,
);

transaction.sign(secretKey, Signature.SIGHASH_ALL, 'ecdsa');
let tx = transaction.serialize(true);

response = await fetch(BITCOIN_NODE_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic '+btoa('devnet:devnet'),
},
body: JSON.stringify({
id: 0,
method: `sendrawtransaction`,
params: [tx],
}),
});
json = await response.json();
let txid = json.result;

return {
statusCode: 200,
body: JSON.stringify(
{
txid,
},
null,
2
),
};
};
17 changes: 17 additions & 0 deletions examples/cbtc/backend/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "cbtc-bridge",
"version": "1.0.0",
"main": "handler.js",
"license": "MIT",
"devDependencies": {
"serverless-offline": "^8.8.0",
"serverless-plugin-typescript": "^2.1.2",
"typescript": "^4.7.2"
},
"dependencies": {
"@stacks/network": "^4.2.1",
"@stacks/transactions": "^4.2.1",
"@hirosystems/orchestra-types": "^1.0.1-beta.1",
"bitcore-lib": "^8.25.28"
}
}
26 changes: 26 additions & 0 deletions examples/cbtc/backend/serverless.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
org: lgalabru
app: cbtc-bridge
service: cbtc-bridge
frameworkVersion: '3'

provider:
name: aws
runtime: nodejs14.x

functions:
wrapBtc:
handler: handler.wrapBtc
events:
- httpApi:
path: /api/v1/wrapBtc
method: post
unwrapBtc:
handler: handler.unwrapBtc
events:
- httpApi:
path: /api/v1/unwrapBtc
method: post

plugins:
- serverless-plugin-typescript
- serverless-offline
Loading

0 comments on commit e195f71

Please sign in to comment.