github.com/MetalBlockchain/metalgo@v1.11.9/snow/engine/avalanche/vertex/builder.go (about) 1 // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. 2 // See the file LICENSE for licensing terms. 3 4 package vertex 5 6 import ( 7 "context" 8 9 "github.com/MetalBlockchain/metalgo/ids" 10 "github.com/MetalBlockchain/metalgo/snow/consensus/avalanche" 11 "github.com/MetalBlockchain/metalgo/utils" 12 "github.com/MetalBlockchain/metalgo/utils/hashing" 13 ) 14 15 // Builder builds a vertex given a set of parentIDs and transactions. 16 type Builder interface { 17 // Build a new stop vertex from the parents 18 BuildStopVtx(ctx context.Context, parentIDs []ids.ID) (avalanche.Vertex, error) 19 } 20 21 // Build a new stateless vertex from the contents of a vertex 22 func Build( 23 chainID ids.ID, 24 height uint64, 25 parentIDs []ids.ID, 26 txs [][]byte, 27 ) (StatelessVertex, error) { 28 return buildVtx( 29 chainID, 30 height, 31 parentIDs, 32 txs, 33 func(vtx innerStatelessVertex) error { 34 return vtx.verify() 35 }, 36 false, 37 ) 38 } 39 40 // Build a new stateless vertex from the contents of a vertex 41 func BuildStopVertex(chainID ids.ID, height uint64, parentIDs []ids.ID) (StatelessVertex, error) { 42 return buildVtx( 43 chainID, 44 height, 45 parentIDs, 46 nil, 47 func(vtx innerStatelessVertex) error { 48 return vtx.verifyStopVertex() 49 }, 50 true, 51 ) 52 } 53 54 func buildVtx( 55 chainID ids.ID, 56 height uint64, 57 parentIDs []ids.ID, 58 txs [][]byte, 59 verifyFunc func(innerStatelessVertex) error, 60 stopVertex bool, 61 ) (StatelessVertex, error) { 62 utils.Sort(parentIDs) 63 utils.SortByHash(txs) 64 65 codecVer := CodecVersion 66 if stopVertex { 67 // use new codec version for the "StopVertex" 68 codecVer = CodecVersionWithStopVtx 69 } 70 71 innerVtx := innerStatelessVertex{ 72 Version: codecVer, 73 ChainID: chainID, 74 Height: height, 75 Epoch: 0, 76 ParentIDs: parentIDs, 77 Txs: txs, 78 } 79 if err := verifyFunc(innerVtx); err != nil { 80 return nil, err 81 } 82 83 vtxBytes, err := Codec.Marshal(innerVtx.Version, innerVtx) 84 vtx := statelessVertex{ 85 innerStatelessVertex: innerVtx, 86 id: hashing.ComputeHash256Array(vtxBytes), 87 bytes: vtxBytes, 88 } 89 return vtx, err 90 }