bitcoinjs学习笔记0(预备知识)
bitcoinjs-lib 是一个用于处理比特币相关操作的 JavaScript 库。它提供了构建、解析和验证比特币交易的工具,支持多种比特币协议功能。我们可以使用bitcoinjs-lib来自定义更复杂的交易。
1.bitcoin-core
1.1 安装
到bitcoin-core官网下载Windows版本的bitcoin-core软件(根据自己的系统下载对应软件),直接使用图形化界面来搭建区块链网络节点
1.2 配置
一般情况下第一次打开软件默认连接的主网,这时软件会连接附近的全节点下载区块链之前的区块数据,数据量好像有600多G,而且比特币十分昂贵,特别是在24年川普重新当选总统后,一个比特币的价格更是突破10万$大关,对于新手建议使用regtest网络,即搭建私链
配置教程参考使用Windows版bitcoin core rpc接口
需要注意的是,修改为regtest网络,需要在bitcoin.conf配置文件中添加以下代码
regtest=1
fallbackfee=0.0002
txindex=1
acceptnonstdtxn=1
然后重新启动bitcoin-core,看到启动界面是蓝色,且带有regtest即启动成功
1.3钱包
一般第一次下载该软件,需要创建一个钱包。在图1-2中点击右下角隐藏,点击创建钱包,或者点击左上角的文件—创建钱包
1.4 控制台&基本命令
在右上角 窗口—控制台打开命令行窗口
使用help查看所有命令,接下来介绍一些常见命令
// 1.获取区块链基本信息
getblockchaininfo
// 2.创建一个新地址,可以直接使用,也可以添加地址类型,如
getnewaddress "myaccount" "legacy"
getnewaddress "myaccount" "p2sh-segwit"
getnewaddress "myaccount" "bech32"
getnewaddress "myaccount" "bech32m"
// 直接使用getnewadress,地址是Native SegWit
3. 运行 generatetoaddress N 地址
- 使用regtest模式下的RPC命令创建n个区块,每创建一个区块就会有相应的测试币奖励;
- 使用比特币默认规则创建的比特币私有链,其奖励机制与testnet不同,在regtest模式下,创建最初的l50个
区块中每个区块能得到50个测试币奖励,接下来150个区块获取奖励25个,此后的每150个区块的奖励减半。 - 一个区块要得到100个确认才能消费被奖励的测试币。所以至少需要产生101个区块,这样第一个区块中 coinbase交易中的测试币才是确认的。(产生101个区块,最终钱包里有50个币)
4. 运行 getblockcount 查看区块总数量
5. 运行 getbalance 查看当前余额
6. 运行 listunspent 查看UTXO(未花费交易输出)
7. sendtoaddress [bitcoin address\] [tx btc num] 执行简单地支出
完整的命令,需要时查询
== Blockchain ==
dumptxoutset "path"
getbestblockhash
getblock "blockhash" ( verbosity )
getblockchaininfo
getblockcount
getblockfilter "blockhash" ( "filtertype" )
getblockfrompeer "blockhash" peer_id
getblockhash height
getblockheader "blockhash" ( verbose )
getblockstats hash_or_height ( stats )
getchainstates
getchaintips
getchaintxstats ( nblocks "blockhash" )
getdeploymentinfo ( "blockhash" )
getdifficulty
getmempoolancestors "txid" ( verbose )
getmempooldescendants "txid" ( verbose )
getmempoolentry "txid"
getmempoolinfo
getrawmempool ( verbose mempool_sequence )
gettxout "txid" n ( include_mempool )
gettxoutproof ["txid",...] ( "blockhash" )
gettxoutsetinfo ( "hash_type" hash_or_height use_index )
gettxspendingprevout [{"txid":"hex","vout":n},...]
importmempool "filepath" ( options )
loadtxoutset "path"
preciousblock "blockhash"
pruneblockchain height
savemempool
scanblocks "action" ( [scanobjects,...] start_height stop_height "filtertype" options )
scantxoutset "action" ( [scanobjects,...] )
verifychain ( checklevel nblocks )
verifytxoutproof "proof"
== Control ==
getmemoryinfo ( "mode" )
getrpcinfo
help ( "command" )
logging ( ["include_category",...] ["exclude_category",...] )
stop
uptime
== Mining ==
getblocktemplate {"mode":"str","capabilities":["str",...],"rules":["segwit","str",...],"longpollid":"str","data":"hex"}
getmininginfo
getnetworkhashps ( nblocks height )
getprioritisedtransactions
prioritisetransaction "txid" ( dummy ) fee_delta
submitblock "hexdata" ( "dummy" )
submitheader "hexdata"
== Network ==
addnode "node" "command" ( v2transport )
clearbanned
disconnectnode ( "address" nodeid )
getaddednodeinfo ( "node" )
getaddrmaninfo
getconnectioncount
getnettotals
getnetworkinfo
getnodeaddresses ( count "network" )
getpeerinfo
listbanned
ping
setban "subnet" "command" ( bantime absolute )
setnetworkactive state
== Rawtransactions ==
analyzepsbt "psbt"
combinepsbt ["psbt",...]
combinerawtransaction ["hexstring",...]
converttopsbt "hexstring" ( permitsigdata iswitness )
createpsbt [{"txid":"hex","vout":n,"sequence":n},...] [{"address":amount,...},{"data":"hex"},...] ( locktime replaceable )
createrawtransaction [{"txid":"hex","vout":n,"sequence":n},...] [{"address":amount,...},{"data":"hex"},...] ( locktime replaceable )
decodepsbt "psbt"
decoderawtransaction "hexstring" ( iswitness )
decodescript "hexstring"
descriptorprocesspsbt "psbt" ["",{"desc":"str","range":n or [n,n]},...] ( "sighashtype" bip32derivs finalize )
finalizepsbt "psbt" ( extract )
fundrawtransaction "hexstring" ( options iswitness )
getrawtransaction "txid" ( verbosity "blockhash" )
joinpsbts ["psbt",...]
sendrawtransaction "hexstring" ( maxfeerate maxburnamount )
signrawtransactionwithkey "hexstring" ["privatekey",...] ( [{"txid":"hex","vout":n,"scriptPubKey":"hex","redeemScript":"hex","witnessScript":"hex","amount":amount},...] "sighashtype" )
submitpackage ["rawtx",...] ( maxfeerate maxburnamount )
testmempoolaccept ["rawtx",...] ( maxfeerate )
utxoupdatepsbt "psbt" ( ["",{"desc":"str","range":n or [n,n]},...] )
== Signer ==
enumeratesigners
== Util ==
createmultisig nrequired ["key",...] ( "address_type" )
deriveaddresses "descriptor" ( range )
estimatesmartfee conf_target ( "estimate_mode" )
getdescriptorinfo "descriptor"
getindexinfo ( "index_name" )
signmessagewithprivkey "privkey" "message"
validateaddress "address"
verifymessage "address" "signature" "message"
== Wallet ==
abandontransaction "txid"
abortrescan
addmultisigaddress nrequired ["key",...] ( "label" "address_type" )
backupwallet "destination"
bumpfee "txid" ( options )
createwallet "wallet_name" ( disable_private_keys blank "passphrase" avoid_reuse descriptors load_on_startup external_signer )
createwalletdescriptor "type" ( {"internal":bool,"hdkey":"str",...} )
dumpprivkey "address"
dumpwallet "filename"
encryptwallet "passphrase"
getaddressesbylabel "label"
getaddressinfo "address"
getbalance ( "dummy" minconf include_watchonly avoid_reuse )
getbalances
gethdkeys ( {"active_only":bool,"private":bool,...} )
getnewaddress ( "label" "address_type" )
getrawchangeaddress ( "address_type" )
getreceivedbyaddress "address" ( minconf include_immature_coinbase )
getreceivedbylabel "label" ( minconf include_immature_coinbase )
gettransaction "txid" ( include_watchonly verbose )
getunconfirmedbalance
getwalletinfo
importaddress "address" ( "label" rescan p2sh )
importdescriptors requests
importmulti requests ( options )
importprivkey "privkey" ( "label" rescan )
importprunedfunds "rawtransaction" "txoutproof"
importpubkey "pubkey" ( "label" rescan )
importwallet "filename"
keypoolrefill ( newsize )
listaddressgroupings
listdescriptors ( private )
listlabels ( "purpose" )
listlockunspent
listreceivedbyaddress ( minconf include_empty include_watchonly "address_filter" include_immature_coinbase )
listreceivedbylabel ( minconf include_empty include_watchonly include_immature_coinbase )
listsinceblock ( "blockhash" target_confirmations include_watchonly include_removed include_change "label" )
listtransactions ( "label" count skip include_watchonly )
listunspent ( minconf maxconf ["address",...] include_unsafe query_options )
listwalletdir
listwallets
loadwallet "filename" ( load_on_startup )
lockunspent unlock ( [{"txid":"hex","vout":n},...] persistent )
migratewallet ( "wallet_name" "passphrase" )
newkeypool
psbtbumpfee "txid" ( options )
removeprunedfunds "txid"
rescanblockchain ( start_height stop_height )
restorewallet "wallet_name" "backup_file" ( load_on_startup )
send [{"address":amount,...},{"data":"hex"},...] ( conf_target "estimate_mode" fee_rate options )
sendall ["address",{"address":amount,...},...] ( conf_target "estimate_mode" fee_rate options )
sendmany ( "" ) {"address":amount,...} ( minconf "comment" ["address",...] replaceable conf_target "estimate_mode" fee_rate verbose )
sendtoaddress "address" amount ( "comment" "comment_to" subtractfeefromamount replaceable conf_target "estimate_mode" avoid_reuse fee_rate verbose )
sethdseed ( newkeypool "seed" )
setlabel "address" "label"
settxfee amount
setwalletflag "flag" ( value )
signmessage "address" "message"
signrawtransactionwithwallet "hexstring" ( [{"txid":"hex","vout":n,"scriptPubKey":"hex","redeemScript":"hex","witnessScript":"hex","amount":amount},...] "sighashtype" )
simulaterawtransaction ( ["rawtx",...] {"include_watchonly":bool,...} )
unloadwallet ( "wallet_name" load_on_startup )
upgradewallet ( version )
walletcreatefundedpsbt ( [{"txid":"hex","vout":n,"sequence":n,"weight":n},...] ) [{"address":amount,...},{"data":"hex"},...] ( locktime options bip32derivs )
walletdisplayaddress "address"
walletlock
walletpassphrase "passphrase" timeout
walletpassphrasechange "oldpassphrase" "newpassphrase"
walletprocesspsbt "psbt" ( sign "sighashtype" bip32derivs finalize )
1.5 重要命令
1. getrawtransaction txid
// 获取交易原始信息(hex格式)
2. decoderawtransaction hex
// 解码原始交易数据(十六进制字符串),并将其转换为可读的 JSON 格式
3. sendrawtransaction hex
// 将交易广播出去
1.6 交易demo
1. getblockchaininfo // 获取链的基本信息
2. getnewaddress // 创建新地址
3. sendtoaddress addr 1 // 向 addr 地址发送一个比特币
4. getrawtransaction txid // 获取交易原始信息(hex格式)
5. decoderawtransaction hex // 解码原始交易数据(十六进制字符串),并将其转换为可读的 JSON 格式
图1-6-2中vin为交易的输入,vout为交易输出,vout数组中第二个对象即为我们转的那一个比特币