资讯专栏INFORMATION COLUMN

Bytom交易说明(UTXO用户自己管理模式)

RyanQ / 1492人阅读

摘要:比原项目仓库地址地址该部分主要针对用户自己管理私钥和地址,并通过来构建和发送交易。其中创建单签地址参考代码进行相应改造为创建多签地址参考代码进行相应改造为找到可花费的找到可花费的,其实就是找到接收地址或接收是你自己的。

比原项目仓库:

Github地址:https://github.com/Bytom/bytom

Gitee地址:https://gitee.com/BytomBlockc...

该部分主要针对用户自己管理私钥和地址,并通过utxo来构建和发送交易。

1.创建私钥和公钥

2.根据公钥创建接收对象

3.找到可花费的utxo

4.通过utxo构造交易

5.组合交易的inputoutput构成交易模板

6.对构造的交易进行签名

7.提交交易上链

注意事项:

以下步骤以及功能改造仅供参考,具体代码实现需要用户根据实际情况进行调试,具体可以参考单元测试案例代码blockchain/txbuilder/txbuilder_test.go#L255

1.创建私钥和公钥

该部分功能可以参考代码crypto/ed25519/chainkd/util.go#L11,可以通过 NewXKeys(nil) 创建主私钥和主公钥

</>复制代码

  1. func NewXKeys(r io.Reader) (xprv XPrv, xpub XPub, err error) {
  2. xprv, err = NewXPrv(r)
  3. if err != nil {
  4. return
  5. }
  6. return xprv, xprv.XPub(), nil
  7. }
2.根据公钥创建接收对象

接收对象包含两种形式:address形式和program形式,两者是一一对应的,任选其一即可。其中创建单签地址参考代码account/accounts.go#L267进行相应改造为:

</>复制代码

  1. func (m *Manager) createP2PKH(xpub chainkd.XPub) (*CtrlProgram, error) {
  2. pubKey := xpub.PublicKey()
  3. pubHash := crypto.Ripemd160(pubKey)
  4. // TODO: pass different params due to config
  5. address, err := common.NewAddressWitnessPubKeyHash(pubHash, &consensus.ActiveNetParams)
  6. if err != nil {
  7. return nil, err
  8. }
  9. control, err := vmutil.P2WPKHProgram([]byte(pubHash))
  10. if err != nil {
  11. return nil, err
  12. }
  13. return &CtrlProgram{
  14. Address: address.EncodeAddress(),
  15. ControlProgram: control,
  16. }, nil
  17. }

创建多签地址参考代码account/accounts.go#L294进行相应改造为:

</>复制代码

  1. func (m *Manager) createP2SH(xpubs []chainkd.XPub) (*CtrlProgram, error) {
  2. derivedPKs := chainkd.XPubKeys(xpubs)
  3. signScript, err := vmutil.P2SPMultiSigProgram(derivedPKs, len(derivedPKs))
  4. if err != nil {
  5. return nil, err
  6. }
  7. scriptHash := crypto.Sha256(signScript)
  8. // TODO: pass different params due to config
  9. address, err := common.NewAddressWitnessScriptHash(scriptHash, &consensus.ActiveNetParams)
  10. if err != nil {
  11. return nil, err
  12. }
  13. control, err := vmutil.P2WSHProgram(scriptHash)
  14. if err != nil {
  15. return nil, err
  16. }
  17. return &CtrlProgram{
  18. Address: address.EncodeAddress(),
  19. ControlProgram: control,
  20. }, nil
  21. }
3.找到可花费的utxo

找到可花费的utxo,其实就是找到接收地址或接收program是你自己的unspend_output。其中utxo的结构为:(参考代码account/reserve.go#L39)

</>复制代码

  1. // UTXO describes an individual account utxo.
  2. type UTXO struct {
  3. OutputID bc.Hash
  4. SourceID bc.Hash
  5. // Avoiding AssetAmount here so that new(utxo) doesn"t produce an
  6. // AssetAmount with a nil AssetId.
  7. AssetID bc.AssetID
  8. Amount uint64
  9. SourcePos uint64
  10. ControlProgram []byte
  11. AccountID string
  12. Address string
  13. ControlProgramIndex uint64
  14. ValidHeight uint64
  15. Change bool
  16. }

涉及utxo构造交易的相关字段说明如下:

SourceID 前一笔关联交易的mux_id, 根据该ID可以定位到前一笔交易的output

AssetID utxo的资产ID

Amount utxo的资产数目

SourcePos 该utxo在前一笔交易的output的位置

ControlProgram utxo的接收program

Address utxo的接收地址

上述这些utxo的字段信息可以从get-block接口返回结果的transaction中找到,其相关的结构体如下:(参考代码api/block_retrieve.go#L26)

</>复制代码

  1. // BlockTx is the tx struct for getBlock func
  2. type BlockTx struct {
  3. ID bc.Hash `json:"id"`
  4. Version uint64 `json:"version"`
  5. Size uint64 `json:"size"`
  6. TimeRange uint64 `json:"time_range"`
  7. Inputs []*query.AnnotatedInput `json:"inputs"`
  8. Outputs []*query.AnnotatedOutput `json:"outputs"`
  9. StatusFail bool `json:"status_fail"`
  10. MuxID bc.Hash `json:"mux_id"`
  11. }
  12. //AnnotatedOutput means an annotated transaction output.
  13. type AnnotatedOutput struct {
  14. Type string `json:"type"`
  15. OutputID bc.Hash `json:"id"`
  16. TransactionID *bc.Hash `json:"transaction_id,omitempty"`
  17. Position int `json:"position"`
  18. AssetID bc.AssetID `json:"asset_id"`
  19. AssetAlias string `json:"asset_alias,omitempty"`
  20. AssetDefinition *json.RawMessage `json:"asset_definition,omitempty"`
  21. Amount uint64 `json:"amount"`
  22. AccountID string `json:"account_id,omitempty"`
  23. AccountAlias string `json:"account_alias,omitempty"`
  24. ControlProgram chainjson.HexBytes `json:"control_program"`
  25. Address string `json:"address,omitempty"`
  26. }

utxo跟get-block返回结果的字段对应关系如下:

</>复制代码

  1. `SourceID` - `json:"mux_id"`
  2. `AssetID` - `json:"asset_id"`
  3. `Amount` - `json:"amount"`
  4. `SourcePos` - `json:"position"`
  5. `ControlProgram` - `json:"control_program"`
  6. `Address` - `json:"address,omitempty"`
4.通过utxo构造交易

通过utxo构造交易就是使用spend_account_unspent_output的方式来花费指定的utxo。

第一步,通过utxo构造交易输入TxInput和签名需要的数据信息SigningInstruction,该部分功能可以参考代码account/builder.go#L169进行相应改造为:

</>复制代码

  1. // UtxoToInputs convert an utxo to the txinput
  2. func UtxoToInputs(xpubs []chainkd.XPub, u *UTXO) (*types.TxInput, *txbuilder.SigningInstruction, error) {
  3. txInput := types.NewSpendInput(nil, u.SourceID, u.AssetID, u.Amount, u.SourcePos, u.ControlProgram)
  4. sigInst := &txbuilder.SigningInstruction{}
  5. if u.Address == "" {
  6. return txInput, sigInst, nil
  7. }
  8. address, err := common.DecodeAddress(u.Address, &consensus.ActiveNetParams)
  9. if err != nil {
  10. return nil, nil, err
  11. }
  12. switch address.(type) {
  13. case *common.AddressWitnessPubKeyHash:
  14. derivedPK := xpubs[0].PublicKey()
  15. sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness([]byte(derivedPK)))
  16. case *common.AddressWitnessScriptHash:
  17. derivedPKs := chainkd.XPubKeys(xpubs)
  18. script, err := vmutil.P2SPMultiSigProgram(derivedPKs, len(derivedPKs))
  19. if err != nil {
  20. return nil, nil, err
  21. }
  22. sigInst.WitnessComponents = append(sigInst.WitnessComponents, txbuilder.DataWitness(script))
  23. default:
  24. return nil, nil, errors.New("unsupport address type")
  25. }
  26. return txInput, sigInst, nil
  27. }

第二步,通过utxo构造交易输出TxOutput
该部分功能可以参考代码protocol/bc/types/txoutput.go#L20:

</>复制代码

  1. // NewTxOutput create a new output struct
  2. func NewTxOutput(assetID bc.AssetID, amount uint64, controlProgram []byte) *TxOutput {
  3. return &TxOutput{
  4. AssetVersion: 1,
  5. OutputCommitment: OutputCommitment{
  6. AssetAmount: bc.AssetAmount{
  7. AssetId: &assetID,
  8. Amount: amount,
  9. },
  10. VMVersion: 1,
  11. ControlProgram: controlProgram,
  12. },
  13. }
  14. }
5.组合交易的input和output构成交易模板

通过上面已经生成的交易信息构造交易txbuilder.Template,该部分功能可以参考blockchain/txbuilder/builder.go#L92进行改造为:

</>复制代码

  1. type InputAndSigInst struct {
  2. input *types.TxInput
  3. sigInst *SigningInstruction
  4. }
  5. // Build build transactions with template
  6. func BuildTx(inputs []InputAndSigInst, outputs []*types.TxOutput) (*Template, *types.TxData, error) {
  7. tpl := &Template{}
  8. tx := &types.TxData{}
  9. // Add all the built outputs.
  10. tx.Outputs = append(tx.Outputs, outputs...)
  11. // Add all the built inputs and their corresponding signing instructions.
  12. for _, in := range inputs {
  13. // Empty signature arrays should be serialized as empty arrays, not null.
  14. in.sigInst.Position = uint32(len(inputs))
  15. if in.sigInst.WitnessComponents == nil {
  16. in.sigInst.WitnessComponents = []witnessComponent{}
  17. }
  18. tpl.SigningInstructions = append(tpl.SigningInstructions, in.sigInst)
  19. tx.Inputs = append(tx.Inputs, in.input)
  20. }
  21. tpl.Transaction = types.NewTx(*tx)
  22. return tpl, tx, nil
  23. }
6.对构造的交易进行签名

账户模型是根据密码找到对应的私钥对交易进行签名,这里用户可以直接使用私钥对交易进行签名,可以参考签名代码blockchain/txbuilder/txbuilder.go#L82进行改造为:(以下改造仅支持单签交易,多签交易用户可以参照该示例进行改造)

</>复制代码

  1. // Sign will try to sign all the witness
  2. func Sign(tpl *Template, xprv chainkd.XPrv) error {
  3. for i, sigInst := range tpl.SigningInstructions {
  4. h := tpl.Hash(uint32(i)).Byte32()
  5. sig := xprv.Sign(h[:])
  6. rawTxSig := &RawTxSigWitness{
  7. Quorum: 1,
  8. Sigs: []json.HexBytes{sig},
  9. }
  10. sigInst.WitnessComponents = append([]witnessComponent(rawTxSig), sigInst.WitnessComponents...)
  11. }
  12. return materializeWitnesses(tpl)
  13. }
7.提交交易上链

该步骤无需更改任何内容,直接参照wiki中提交交易的APIsubmit-transaction的功能即可

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/24255.html

相关文章

  • Bytom设计结构解读

    摘要:一引文设计数据结构,组合了许多技术点,如,,,,,,等。采用树,其中的数据可快速证明,可以快速证明每一份状态机是否一致。四是在状态机的转化过程被启动运行,也就是这一步骤。是指发布该资产时需要执行的程序。的逻辑结构则是用二叉树来管理。 一、引文 设计Bytom 数据结构,组合了许多技术点,如 patricia tree,utxo, bvm, account model,protobuf,...

    xuexiangjys 评论0 收藏0
  • 比原链合约入门教程

    摘要:比原项目仓库地址地址一合约简述是的一种智能合约语言,是一门声明性谓词语言。详细说明请参考官方合约相关介绍。编译合约,返回结果便是可锁定的合约。三解锁合约流程合约交易被区块打包成功之后,可以查看具体的合约交易内容,找到对应的。 比原项目仓库: Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBl...

    brianway 评论0 收藏0
  • 使用Java SDK实现离线签名

    摘要:当使用构建完成一笔交易并签名后,若没有全节点的帮助,也需要自己实现网络协议将交易广播到其他节点。其中,第一个依赖是的封装,可用于查询可用的以及提交交易第二个依赖用于构建交易以及对交易进行离线签名。 严格来说,tx-signer并不属于SDK,它是bytomd中构建交易、对交易签名两大模块的java实现版。因此,若想用tx-signer对交易进行离线签名,需要由你在本地保管好自己的私钥。...

    dreamGong 评论0 收藏0
  • 调用Bytom Chrome插件钱包开发Dapp

    摘要:流程总结就是下载安装插件钱包,如果自己的不需要跳过这一步。然后将编译后的合约参数配置在的配置文件,如下图全红部分是测试网合约配置参数调用插件钱包。开发出优秀的应用。 安装使用插件钱包 1. 打开Google浏览器的应用商店,搜索Bystore showImg(https://segmentfault.com/img/bVbq0Ol?w=2554&h=1312); 下载链接:http:/...

    Mike617 评论0 收藏0
  • Derek解读Bytom源码-持久化存储LevelDB

    摘要:函数总共操作有两步从缓存中查询值,如果查到则返回如果为从缓存中查询到则回调回调函数。回调函数会将从磁盘上获得到块信息存储到缓存中并返回该块的信息。回调函数实际上调取的是下的,它会从磁盘中获取信息并返回。 作者:Derek 简介 Github地址:https://github.com/Bytom/bytom Gitee地址:https://gitee.com/BytomBlockc......

    Eminjannn 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<