github.com/Bytom/bytom@v1.1.2-0.20210127130405-ae40204c0b09/protocol/bc/types/spend_test.go (about) 1 package types 2 3 import ( 4 "bytes" 5 "encoding/hex" 6 "strings" 7 "testing" 8 9 "github.com/davecgh/go-spew/spew" 10 11 "github.com/bytom/bytom/encoding/blockchain" 12 "github.com/bytom/bytom/protocol/bc" 13 "github.com/bytom/bytom/testutil" 14 ) 15 16 func TestSerializationSpendCommitment(t *testing.T) { 17 assetID := testutil.MustDecodeAsset("81756fdab39a17163b0ce582ee4ee256fb4d1e156c692b997d608a42ecb38d47") 18 sc := &SpendCommitment{ 19 AssetAmount: bc.AssetAmount{ 20 AssetId: &assetID, 21 Amount: 254354, 22 }, 23 SourceID: testutil.MustDecodeHash("bef8ff450b877df84174ac5c279fc97da0f507ffe7beef7badf116ea9e2ff041"), 24 SourcePosition: 3, 25 VMVersion: 1, 26 ControlProgram: []byte("TestSerializationSpendCommitment"), 27 } 28 29 wantHex := strings.Join([]string{ 30 "66", // serialization length 31 "bef8ff450b877df84174ac5c279fc97da0f507ffe7beef7badf116ea9e2ff041", // sourceID 32 "81756fdab39a17163b0ce582ee4ee256fb4d1e156c692b997d608a42ecb38d47", // assetID 33 "92c30f", // amount 34 "03", // position 35 "01", // version 36 "20", // control program length 37 "5465737453657269616c697a6174696f6e5370656e64436f6d6d69746d656e74", // control program 38 }, "") 39 40 // Test convert struct to hex 41 var buffer bytes.Buffer 42 suffix := []byte{} 43 if err := sc.writeExtensibleString(&buffer, suffix, 1); err != nil { 44 t.Fatal(err) 45 } else if len(suffix) != 0 { 46 t.Errorf("spend commitment write to got garbage hex left") 47 } 48 49 gotHex := hex.EncodeToString(buffer.Bytes()) 50 if gotHex != wantHex { 51 t.Errorf("serialization bytes = %s want %s", gotHex, wantHex) 52 } 53 54 // Test convert hex to struct 55 var gotSC SpendCommitment 56 decodeHex, err := hex.DecodeString(wantHex) 57 if err != nil { 58 t.Fatal(err) 59 } 60 61 if getSuffix, err := gotSC.readFrom(blockchain.NewReader(decodeHex), 1); err != nil { 62 t.Fatal(err) 63 } else if len(getSuffix) != 0 { 64 t.Errorf("spend commitment read from got garbage hex left") 65 } 66 67 if !testutil.DeepEqual(*sc, gotSC) { 68 t.Errorf("expected marshaled/unmarshaled spend commitment to be:\n%sgot:\n%s", spew.Sdump(*sc), spew.Sdump(gotSC)) 69 } 70 }