github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/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  		StateData:      [][]byte{[]byte("TestStateData")},
    28  	}
    29  
    30  	wantHex := strings.Join([]string{
    31  		"75", // serialization length
    32  		"bef8ff450b877df84174ac5c279fc97da0f507ffe7beef7badf116ea9e2ff041", // sourceID
    33  		"81756fdab39a17163b0ce582ee4ee256fb4d1e156c692b997d608a42ecb38d47", // assetID
    34  		"92c30f", // amount
    35  		"03",     // position
    36  		"01",     // version
    37  		"20",     // control program length
    38  		"5465737453657269616c697a6174696f6e5370656e64436f6d6d69746d656e74", // control program
    39  		"010d",                       // stata data length
    40  		"54657374537461746544617461", // state data
    41  	}, "")
    42  
    43  	// Test convert struct to hex
    44  	var buffer bytes.Buffer
    45  	suffix := []byte{}
    46  	if err := sc.writeExtensibleString(&buffer, suffix, 1); err != nil {
    47  		t.Fatal(err)
    48  	} else if len(suffix) != 0 {
    49  		t.Errorf("spend commitment write to got garbage hex left")
    50  	}
    51  
    52  	gotHex := hex.EncodeToString(buffer.Bytes())
    53  	if gotHex != wantHex {
    54  		t.Errorf("serialization bytes = %s want %s", gotHex, wantHex)
    55  	}
    56  
    57  	// Test convert hex to struct
    58  	var gotSC SpendCommitment
    59  	decodeHex, err := hex.DecodeString(wantHex)
    60  	if err != nil {
    61  		t.Fatal(err)
    62  	}
    63  
    64  	if getSuffix, err := gotSC.readFrom(blockchain.NewReader(decodeHex), 1); err != nil {
    65  		t.Fatal(err)
    66  	} else if len(getSuffix) != 0 {
    67  		t.Errorf("spend commitment read from got garbage hex left")
    68  	}
    69  
    70  	if !testutil.DeepEqual(*sc, gotSC) {
    71  		t.Errorf("expected marshaled/unmarshaled spend commitment to be:\n%sgot:\n%s", spew.Sdump(*sc), spew.Sdump(gotSC))
    72  	}
    73  }