Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add demo code for brc20 #1045

Merged
merged 1 commit into from
Mar 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions BTC/BRC-20/demo-code/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Oghenovo Usiwoma

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
72 changes: 72 additions & 0 deletions BTC/BRC-20/demo-code/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# brc20-demo-code

## 运行方式:

node 切换到 v20 以上

```
yarn install
yarn dev src/index.ts
```



## 部分代码说明

此demo是参考

### index.ts说明

```ts
import {
initEccLib,
payments,
} from "bitcoinjs-lib";
import { ECPairFactory, ECPairAPI } from 'ecpair';
import * as tinysecp from 'tiny-secp256k1';
import networks from "./networks";


import { startP2tr } from './demo/startP2tr';
import { startTapTree } from './demo/startTapTree';
import { startInscribeDeploy } from './demo/startInscribe_deploy';
import { startInscribeTransfer } from './demo/startInscribe_transfer';
import { startInscribeMint } from './demo/startInscribe_mint';
import { startInscribeMintWithNoSdk } from './demo/startInscribe_mint_no_sdk';

import dotEnv from 'dotenv';
import { addressToScriptPubKey, decodeScript } from "./utils";
dotEnv.config();

initEccLib(tinysecp as any);
const ECPair: ECPairAPI = ECPairFactory(tinysecp);
const network = networks.testnet;

async function start() {

const privateKey = process.env.secret;
const keypair = ECPair.fromWIF(privateKey, network);
console.log("secretK = " + keypair.privateKey?.toString('hex'));
console.log("publicK = " + keypair.publicKey?.toString('hex'));
console.log("\r\n");

await startP2tr(keypair); // 介绍了taproot地址是怎么生成以及怎么进行转账的
// await startTapTree(keypair); // 参考博客文章,对taproot的脚本创建以,花费taproot地址上的交易进行demo
// await startInscribeDeploy(keypair) // deploy一个brc20的铭文
// await startInscribeMint(keypair) // mint一个brc20的铭文
// await startInscribeTransfer(keypair); // 揭露一个transfer的brc20铭文
// await startInscribeMintWithNoSdk(keypair) // 不用sdk,来mint brc20铭文
}

start().then(() => process.exit());
```







## 参考文章:

- https://dev.to/eunovo/a-guide-to-creating-taproot-scripts-with-bitcoinjs-lib-4oph
29 changes: 29 additions & 0 deletions BTC/BRC-20/demo-code/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"name": "taproot-with-bitcoinjs",
"version": "1.0.0",
"type": "module",
"main": "dist/index.js",
"license": "MIT",
"devDependencies": {
"@types/node": "^18.13.0",
"ts-node": "^10.9.1",
"typescript": "^4.9.5"
},
"dependencies": {
"@cmdcode/buff-utils": "^1.9.7",
"@cmdcode/crypto-utils": "~2.0.2",
"@cmdcode/tapscript": "^1.4.4",
"axios": "^1.3.2",
"bitcoinjs-lib": "^6.1.0",
"dotenv": "^16.3.2",
"ecpair": "^2.1.0",
"ethereumjs-util": "^7.1.5",
"tiny-secp256k1": "^2.2.1",
"varuint-bitcoin": "^1.1.2"
},
"scripts": {
"build": "tsc --noEmitOnError",
"dev": "node --trace-deprecation --no-warnings --loader ts-node/esm",
"debug": "node --inspect-brk --trace-deprecation --no-warnings --loader ts-node/esm"
}
}
130 changes: 130 additions & 0 deletions BTC/BRC-20/demo-code/src/blockstream_utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import axios, { AxiosResponse } from "axios";

const blockstream = new axios.Axios({
baseURL: `https://blockstream.info/testnet/api`,
proxy: false
});

export async function waitUntilUTXO(address: string) {
return new Promise<IUTXO[]>((resolve, reject) => {
let intervalId: any;
const checkForUtxo = async () => {
try {
const response: AxiosResponse<string> = await blockstream.get(`/address/${address}/utxo`);
const data: IUTXO[] = response.data ? JSON.parse(response.data) : undefined;
// console.log(`utxos = `, data);
if (data.length > 0) {
resolve(data);
clearInterval(intervalId);
}
} catch (error) {
reject(error);
clearInterval(intervalId);
}
};
intervalId = setInterval(checkForUtxo, 10000);
});
}

export async function broadcast(txHex: string) {
const response: AxiosResponse<string> = await blockstream.post('/tx', txHex);
return response.data;
}


export async function getTxData(txid: string) {
return new Promise<ITxData>((resolve, reject) => {
let intervalId: any;
const fetchTxData = async () => {
try {
const response: AxiosResponse<string> = await blockstream.get(`/tx/${txid}`);
const data: ITxData = response.data ? JSON.parse(response.data) : undefined;
if (data) {
resolve(data);
clearInterval(intervalId);
}
} catch (error) {
reject(error);
clearInterval(intervalId);
}
};
intervalId = setInterval(fetchTxData, 10000);
});
}

export async function getTxHex(txid: string) {
return new Promise<string>((resolve, reject) => {
let intervalId: any;
const fetchTxData = async () => {
try {
const response: AxiosResponse<string> = await blockstream.get(`/tx/${txid}/hex`);
// console.log(`getTxHex response = `, response)
const data: string = response.data ? response.data : undefined;
if (data) {
resolve(data);
clearInterval(intervalId);
}
} catch (error) {
reject(error);
clearInterval(intervalId);
}
};
intervalId = setInterval(fetchTxData, 10000);
});
}

interface IUTXO {
txid: string;
vout: number;
status: {
confirmed: boolean;
block_height: number;
block_hash: string;
block_time: number;
};
value: number;
}


export interface Prevout {
scriptpubkey: string;
scriptpubkey_asm: string;
scriptpubkey_type: string;
scriptpubkey_address: string;
value: number;
}

export interface Vin {
txid: string;
vout: number;
prevout: Prevout;
scriptsig: string;
scriptsig_asm: string;
witness: string[];
is_coinbase: boolean;
sequence: number;
}

export interface Vout {
scriptpubkey: string;
scriptpubkey_asm: string;
scriptpubkey_type: string;
scriptpubkey_address: string;
value: number;
}

export interface Statu {
confirmed: boolean;
}

export interface ITxData {
txid: string;
version: number;
locktime: number;
vin: Vin[];
vout: Vout[];
size: number;
weight: number;
fee: number;
status: Statu;
}
92 changes: 92 additions & 0 deletions BTC/BRC-20/demo-code/src/demo/startInscribe_deploy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { Buff } from '@cmdcode/buff-utils'
import { broadcast, waitUntilUTXO } from "../blockstream_utils";
import { Address, Signer, Tap, Tx, } from '@cmdcode/tapscript'
import { ECPairInterface } from 'ecpair';
import { toXOnly } from '../utils';



/**
* 注:以下代码里里,我用了@cmdcode/tapscript的sdk,不再是coinjs-lib的原生代码
* @param keypair
*/
export async function startInscribeDeploy(keypair: ECPairInterface) {
// TapTree example
console.log(`Running "Inscribe example"`);

// The 'marker' bytes. Part of the ordinal inscription format.
const marker = Buff.encode('ord')
/* Specify the media type of the file. Applications use this when rendering
* content. See: https://developer.mozilla.org/en-US/docs/Glossary/MIME_type
*/
const mimetype = Buff.encode('text/plain')
const textdata = Buff.encode(`{ "p": "brc-20", "op": "deploy", "tick": "coda", "max": "21000000", "lim": "1000" }`);

const pubkey = toXOnly(keypair.publicKey)
// Basic format of an 'inscription' script.
const script = [pubkey, 'OP_CHECKSIG', 'OP_0', 'OP_IF', marker, mimetype, textdata, 'OP_ENDIF']
// For tapscript spends, we need to convert this script into a 'tapleaf'.
const tapleaf = Tap.encodeScript(script)
console.log('tapleaf:', tapleaf)
// 生成一个taproot的地址
// Generate a tapkey that includes our leaf script. Also, create a merlke proof
// (cblock) that targets our leaf and proves its inclusion in the tapkey.
const [tpubkey, cblock] = Tap.getPubKey(pubkey, { target: tapleaf })
// A taproot address is simply the tweaked public key, encoded in bech32 format.
const address = Address.p2tr.fromPubKey(tpubkey, 'testnet')
console.log('Your address:', address)


/* 现在,发送100_000 sats到上面这个地址。
并且记录下txid 和vount
然后在redeem的时候填上这些信息
* NOTE: To continue with this example, send 100_000 sats to the above address.
* You will also need to make a note of the txid and vout of that transaction,
* so that you can include that information below in the redeem tx.
*/

// 从这个地址上给上面账户打钱
const utxos = await waitUntilUTXO(address);
console.log(`Using UTXO ${utxos[0].txid}:${utxos[0].vout}`);

const txdata = Tx.create({
vin: [{
// Use the txid of the funding transaction used to send the sats.
txid: utxos[0].txid,
// Specify the index value of the output that you are going to spend from.
vout: utxos[0].vout,
// Also include the value and script of that ouput.
prevout: {
// Feel free to change this if you sent a different amount.
value: 1100,
// This is what our address looks like in script form.
scriptPubKey: [tpubkey]
},
}],
vout: [{
// We are leaving behind 1000 sats as a fee to the miners.
value: 1000,
// This is the new script that we are locking our funds to. 发的一个地址
scriptPubKey: Address.toScriptPubKey('tb1plf84y3ak54k6m3kr9rzka9skynkn5mhfjmaenn70epdzamtgpadqu8uxx9')
}]
})

// For this example, we are signing for input 0 of our transaction,
// using the untweaked secret key. We are also extending the signature
// to include a commitment to the tapleaf script that we wish to use.
const sig = Signer.taproot.sign(keypair.privateKey!.toString('hex'), txdata, 0, { extension: tapleaf })

// Add the signature to our witness data for input 0, along with the script
// and merkle proof (cblock) for the script.
txdata.vin[0].witness = [sig, script, cblock]

// Check if the signature is valid for the provided public key, and that the
// transaction is also valid (the merkle proof will be validated as well).
const isValid = Signer.taproot.verify(txdata, 0, { pubkey, throws: true })

console.log('Your txhex:', Tx.encode(txdata).hex)
console.dir(txdata, { depth: null })
console.log('Transaction should pass validation.', isValid)
let txid = await broadcast(Tx.encode(txdata).hex);
console.log(`Success! Txid is ${txid}`);
}
Loading
Loading