OSDN Git Service

add logs for debug (#545)
[bytom/bytom.git] / protocol / tx_test.go
1 package protocol
2
3 import (
4         "fmt"
5         "testing"
6
7         "golang.org/x/crypto/sha3"
8
9         "github.com/bytom/crypto/ed25519"
10         "github.com/bytom/protocol/bc"
11         "github.com/bytom/protocol/bc/types"
12         "github.com/bytom/protocol/vm"
13         "github.com/bytom/protocol/vm/vmutil"
14         "github.com/bytom/testutil"
15 )
16
17 type testDest struct {
18         privKey ed25519.PrivateKey
19 }
20
21 func newDest(t testing.TB) *testDest {
22         _, priv, err := ed25519.GenerateKey(nil)
23         if err != nil {
24                 testutil.FatalErr(t, err)
25         }
26         return &testDest{
27                 privKey: priv,
28         }
29 }
30
31 func (d *testDest) sign(t testing.TB, tx *types.Tx, index uint32) {
32         txsighash := tx.SigHash(index)
33         prog, _ := vm.Assemble(fmt.Sprintf("0x%x TXSIGHASH EQUAL", txsighash.Bytes()))
34         h := sha3.Sum256(prog)
35         sig := ed25519.Sign(d.privKey, h[:])
36         tx.Inputs[index].SetArguments([][]byte{vm.Int64Bytes(0), sig, prog})
37 }
38
39 func (d testDest) controlProgram() ([]byte, error) {
40         pub := d.privKey.Public().(ed25519.PublicKey)
41         return vmutil.P2SPMultiSigProgram([]ed25519.PublicKey{pub}, 1)
42 }
43
44 type testAsset struct {
45         bc.AssetID
46         testDest
47 }
48
49 func newAsset(t testing.TB) *testAsset {
50         dest := newDest(t)
51         cp, _ := dest.controlProgram()
52         assetID := bc.ComputeAssetID(cp, 1, &bc.EmptyStringHash)
53
54         return &testAsset{
55                 AssetID:  assetID,
56                 testDest: *dest,
57         }
58 }
59
60 func issue(t testing.TB, asset *testAsset, dest *testDest, amount uint64) (*types.Tx, *testAsset, *testDest) {
61         if asset == nil {
62                 asset = newAsset(t)
63         }
64         if dest == nil {
65                 dest = newDest(t)
66         }
67         assetCP, _ := asset.controlProgram()
68         destCP, _ := dest.controlProgram()
69         tx := types.NewTx(types.TxData{
70                 Version: 1,
71                 Inputs: []*types.TxInput{
72                         types.NewIssuanceInput([]byte{1}, amount, assetCP, nil, nil),
73                 },
74                 Outputs: []*types.TxOutput{
75                         types.NewTxOutput(asset.AssetID, amount, destCP),
76                 },
77         })
78         asset.sign(t, tx, 0)
79
80         return tx, asset, dest
81 }