Bytom交易说明(UTXO用户自己管理模式)
朋友一起走
发表于 2022-11-13 23:52:55
143
0
0
Github地址:https://github.com/Bytom/bytom8 v" t# ]( n6 a9 v; [5 ]
Gitee地址:https://gitee.com/BytomBlockchain/bytom
该部分主要针对用户自己管理私钥和地址,并通过utxo来构建和发送交易。
1.创建私钥和公钥2.根据公钥创建接收对象3.找到可花费的utxo4.通过utxo构造交易5.组合交易的input和output构成交易模板6.对构造的交易进行签名7.提交交易上链8 Y9 F! p5 Q8 N5 `
注意事项:6 W2 ?5 ~0 j, w! d U, r
以下步骤以及功能改造仅供参考,具体代码实现需要用户根据实际情况进行调试,具体可以参考单元测试案例代码blockchain/txbuilder/txbuilder_test.go#L2552 T0 K3 |. Q" B2 }2 a
1.创建私钥和公钥
该部分功能可以参考代码crypto/ed25519/chainkd/util.go#L11,可以通过 NewXKeys(nil) 创建主私钥和主公钥
func NewXKeys(r io.Reader) (xprv XPrv, xpub XPub, err error) {
xprv, err = NewXPrv(r): ]: @# g1 x: ]5 X! ]
if err != nil {
return; Q3 J9 R0 y4 w" H- n
}
return xprv, xprv.XPub(), nil
}2 u5 b# Q3 a& y, P t' T* o6 V: @
2.根据公钥创建接收对象: b5 Z* q: M7 W
接收对象包含两种形式:address形式和program形式,两者是一一对应的,任选其一即可。其中创建单签地址参考代码account/accounts.go#L267进行相应改造为:( n1 h; H3 `# f& c+ m, l7 g
func (m *Manager) createP2PKH(xpub chainkd.XPub) (*CtrlProgram, error) {2 e1 Y; d0 N' i8 R. O! t
pubKey := xpub.PublicKey()+ F# X" r) c" z$ _1 J0 ] ~
pubHash := crypto.Ripemd160(pubKey)7 n, W2 L/ l/ { ?! l
// TODO: pass different params due to config
address, err := common.NewAddressWitnessPubKeyHash(pubHash, &consensus.ActiveNetParams)6 l) l- g! w3 L
if err != nil {
return nil, err Y1 F9 i) ]5 A9 g
}2 N3 \' u1 ]* _0 x5 C" @
control, err := vmutil.P2WPKHProgram([]byte(pubHash))
if err != nil {
return nil, err
}5 O! A9 I7 H3 N& Q# _; y/ |
return &CtrlProgram{
Address: address.EncodeAddress(),
ControlProgram: control,
}, nil; z" R( S9 M( X: Q
}8 c( M- B- X1 n9 a; @/ F+ Y/ G! B- p
创建多签地址参考代码account/accounts.go#L294进行相应改造为: m D( o# c/ q* e
func (m *Manager) createP2SH(xpubs []chainkd.XPub) (*CtrlProgram, error) {" y( U9 k2 J! R0 z& T0 D
derivedPKs := chainkd.XPubKeys(xpubs)5 }; S( z3 s, I: ^( |; `
signScript, err := vmutil.P2SPMultiSigProgram(derivedPKs, len(derivedPKs))
if err != nil {
return nil, err0 D2 \" ^8 n- `1 h2 d$ N
}# e3 w7 d) f( D, C
scriptHash := crypto.Sha256(signScript)1 V: G1 B! q: _) b3 z
// TODO: pass different params due to config
address, err := common.NewAddressWitnessScriptHash(scriptHash, &consensus.ActiveNetParams); s9 I2 K$ y) U1 D" e, H
if err != nil {
return nil, err
}' @4 F0 l# y* k2 V; v1 b
control, err := vmutil.P2WSHProgram(scriptHash)* o& c+ `/ i/ U7 e' }
if err != nil {
return nil, err, F: Z) R! k0 L4 ]
}2 D( Q6 L9 X& q3 v
return &CtrlProgram{
Address: address.EncodeAddress(),% d% d4 T+ l9 M
ControlProgram: control,* W. P9 U3 S/ I8 A! L
}, nil5 m( m9 o4 d$ G! U
}! M! t8 n/ n8 w3 O7 z7 U
3.找到可花费的utxo
找到可花费的utxo,其实就是找到接收地址或接收program是你自己的unspend_output。其中utxo的结构为:(参考代码account/reserve.go#L39)
// UTXO describes an individual account utxo.
type UTXO struct {
OutputID bc.Hash% I% _$ ^! b& N5 O+ B2 M' N
SourceID bc.Hash
// Avoiding AssetAmount here so that new(utxo) doesn't produce an& E* j& S" p5 d- i
// AssetAmount with a nil AssetId.
AssetID bc.AssetID
Amount uint64
SourcePos uint64: {! h2 v( t5 q' X3 W
ControlProgram []byte( R' E+ T5 l. C/ ~/ F5 d
AccountID string
Address string
ControlProgramIndex uint647 l C3 ~* M/ E) x0 s5 x5 W' t
ValidHeight uint64
Change bool4 ?* E# o" p: s1 @7 ?, H* [
}
涉及utxo构造交易的相关字段说明如下:$ n# R! T# e, b d5 S
SourceID 前一笔关联交易的mux_id, 根据该ID可以定位到前一笔交易的outputAssetID utxo的资产IDAmount utxo的资产数目SourcePos 该utxo在前一笔交易的output的位置ControlProgram utxo的接收programAddress utxo的接收地址
2 I$ b" _" ?- d5 {- @" F
上述这些utxo的字段信息可以从get-block接口返回结果的transaction中找到,其相关的结构体如下:(参考代码api/block_retrieve.go#L26)
// BlockTx is the tx struct for getBlock func
type BlockTx struct {4 p! P8 v4 z& `% ?7 ?" k+ z1 [
ID bc.Hash `json:"id"`7 i7 ~: g9 O' O8 Z8 w2 o8 o
Version uint64 `json:"version"`& C% g9 s0 Y4 \' H* j+ t5 K( q1 y' q
Size uint64 `json:"size"`
TimeRange uint64 `json:"time_range"`. ^1 Z% J4 f; ?* [( F
Inputs []*query.AnnotatedInput `json:"inputs"`
Outputs []*query.AnnotatedOutput `json:"outputs"`
StatusFail bool `json:"status_fail"`3 k o. x* N# ]
MuxID bc.Hash `json:"mux_id"`
}
//AnnotatedOutput means an annotated transaction output.
type AnnotatedOutput struct {( `5 _" j& r8 \2 B( Y
Type string `json:"type"`+ {, P c5 V! E: g, e
OutputID bc.Hash `json:"id"`7 V h- }$ L: j0 U( e5 G5 Y( ?
TransactionID *bc.Hash `json:"transaction_id,omitempty"`
Position int `json:"position"`
AssetID bc.AssetID `json:"asset_id"`- \# y. }0 c4 v8 F/ X' f
AssetAlias string `json:"asset_alias,omitempty"`
AssetDefinition *json.RawMessage `json:"asset_definition,omitempty"`
Amount uint64 `json:"amount"`
AccountID string `json:"account_id,omitempty"`/ V) ~' Y% I; o( n# m P
AccountAlias string `json:"account_alias,omitempty"`
ControlProgram chainjson.HexBytes `json:"control_program"`
Address string `json:"address,omitempty"`
}' t3 y: J( P; ?3 D- S
utxo跟get-block返回结果的字段对应关系如下:. _# U; c( L6 s# o. q+ Y6 J
`SourceID` - `json:"mux_id"`
`AssetID` - `json:"asset_id"`7 J) C2 O( W$ a+ j- }' S% X1 y
`Amount` - `json:"amount"`
`SourcePos` - `json:"position"`. d5 L6 v! q- j/ k* `
`ControlProgram` - `json:"control_program"`/ \: ]3 x" H# l( C; B/ d
`Address` - `json:"address,omitempty"`0 j" d1 d6 \# o$ r8 x. |6 z
4.通过utxo构造交易2 `- H9 Q" k5 n" a$ V* w9 I( Q
通过utxo构造交易就是使用spend_account_unspent_output的方式来花费指定的utxo。
第一步,通过utxo构造交易输入TxInput和签名需要的数据信息SigningInstruction,该部分功能可以参考代码account/builder.go#L169进行相应改造为:
// UtxoToInputs convert an utxo to the txinput; ~* g7 [+ |3 _+ P! m5 u" u7 n, G; {
func UtxoToInputs(xpubs []chainkd.XPub, u *UTXO) (*types.TxInput, *txbuilder.SigningInstruction, error) {2 _; n; e* }6 L1 Q4 I+ u2 A- F9 g
txInput := types.NewSpendInput(nil, u.SourceID, u.AssetID, u.Amount, u.SourcePos, u.ControlProgram)9 `, C/ g0 |- o4 I, {
sigInst := &txbuilder.SigningInstruction{}. R/ H8 h, f, P: n0 ~8 c1 M8 R
if u.Address == "" {
return txInput, sigInst, nil: x" [ v6 x5 c- t1 k
}; n0 h/ s- x, h7 E
address, err := common.DecodeAddress(u.Address, &consensus.ActiveNetParams)7 S3 a) ^% v9 O, B5 F, \" t
if err != nil {
return nil, nil, err r8 Y) e7 i' x D D" `; B! ]
}3 d7 H2 V% {# S! L
switch address.(type) {( H' G$ I2 O! f6 \& A0 U
case *common.AddressWitnessPubKeyHash:5 J7 e" Q0 ^5 D
derivedPK := xpubs[0].PublicKey()# o0 L9 m( }# ^; R/ f1 K e
sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness([]byte(derivedPK)))
case *common.AddressWitnessScriptHash:
derivedPKs := chainkd.XPubKeys(xpubs)1 m' J! ?! X& f( M& [+ s2 C/ g: e
script, err := vmutil.P2SPMultiSigProgram(derivedPKs, len(derivedPKs))
if err != nil {; P( w; a. n9 ~9 x
return nil, nil, err9 u- g) O8 j* X. k! O) \5 g
} T" }/ n1 m0 _9 z
sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness(script))2 o2 K8 w( g' r: v. l( @/ z2 D8 ?5 r
default:
return nil, nil, errors.New("unsupport address type")) H) s3 Q7 [$ w, H4 \: s" L. E3 n7 I
}
return txInput, sigInst, nil
}$ {$ }7 z1 M& H) r8 B G
第二步,通过utxo构造交易输出TxOutput, F6 d) S! W# ~) b8 f) J$ ^/ X, U
该部分功能可以参考代码protocol/bc/types/txoutput.go#L20:
// NewTxOutput create a new output struct
func NewTxOutput(assetID bc.AssetID, amount uint64, controlProgram []byte) *TxOutput {
return &TxOutput{
AssetVersion: 1,7 [ D. L& Q0 T3 l6 e5 }8 w
OutputCommitment: OutputCommitment{
AssetAmount: bc.AssetAmount{
AssetId: &assetID,6 `6 }% z2 G# u2 g. } R1 L7 ]
Amount: amount,
},' g$ x' m' n" h7 a
VMVersion: 1,1 Q, h7 _7 d' k& F/ N4 @" w) I9 v
ControlProgram: controlProgram,
},1 I+ z, K( d/ y
}
}
5.组合交易的input和output构成交易模板
通过上面已经生成的交易信息构造交易txbuilder.Template,该部分功能可以参考blockchain/txbuilder/builder.go#L92进行改造为:8 g7 F z! ^/ ]8 x) Y# c1 Q) B
type InputAndSigInst struct {
input *types.TxInput
sigInst *SigningInstruction% d) F T( G4 `( x+ |
}
// Build build transactions with template
func BuildTx(inputs []InputAndSigInst, outputs []*types.TxOutput) (*Template, *types.TxData, error) {
tpl := &Template{}
tx := &types.TxData{}; D9 D8 e9 U4 G. K
// Add all the built outputs.
tx.Outputs = append(tx.Outputs, outputs...)( A7 w7 M, z1 y5 i# K6 }
// Add all the built inputs and their corresponding signing instructions.4 m- S, y! `* O8 E# T3 ?
for _, in := range inputs {% m% u" Y% T8 W5 ?1 C+ _9 R) j
// Empty signature arrays should be serialized as empty arrays, not null.
in.sigInst.Position = uint32(len(inputs))6 s* n/ M" i, u4 O
if in.sigInst.WitnessComponents == nil {
in.sigInst.WitnessComponents = []witnessComponent{}0 h: ? Q; m3 A7 L8 z- a( ^$ C4 Y
}$ y0 l/ i5 q. r+ n2 ^
tpl.SigningInstructions = append(tpl.SigningInstructions, in.sigInst)5 w6 h0 [# r, V: r" P! {/ {1 ]) J$ R
tx.Inputs = append(tx.Inputs, in.input)
}
tpl.Transaction = types.NewTx(*tx)
return tpl, tx, nil
}
6.对构造的交易进行签名
账户模型是根据密码找到对应的私钥对交易进行签名,这里用户可以直接使用私钥对交易进行签名,可以参考签名代码blockchain/txbuilder/txbuilder.go#L82进行改造为:(以下改造仅支持单签交易,多签交易用户可以参照该示例进行改造)* f3 i# n8 H: W+ }# ^+ p
// Sign will try to sign all the witness h6 {5 b k$ Q$ `* B3 b3 Z
func Sign(tpl *Template, xprv chainkd.XPrv) error {' R7 `* [3 R0 n. s: d! |" T
for i, sigInst := range tpl.SigningInstructions {( t) I- ^. y, t1 X& _
h := tpl.Hash(uint32(i)).Byte32()
sig := xprv.Sign(h[:])
rawTxSig := &RawTxSigWitness{6 F! A8 s$ b! k9 [/ x( A
Quorum: 1,
Sigs: []json.HexBytes{sig},
}" ^9 @: @7 v0 G5 D6 F( X; t
sigInst.WitnessComponents = append([]witnessComponent(rawTxSig), sigInst.WitnessComponents...)+ z0 F& s: n! `! P
}
return materializeWitnesses(tpl)8 U. v2 A9 g% P+ K- [2 u( V v, a
}
7.提交交易上链6 J5 o# Q1 i5 n9 f
该步骤无需更改任何内容,直接参照wiki中提交交易的APIsubmit-transaction的功能即可3 B8 B7 G# O* G3 t. o0 g' n
成为第一个吐槽的人