/
signed_transaction.go
102 lines (82 loc) · 2.36 KB
/
signed_transaction.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// +build !nosigning
package transactions
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"fmt"
"time"
"github.com/VIZ-Blockchain/viz-go-lib/encoding/transaction"
"github.com/VIZ-Blockchain/viz-go-lib/operations"
"github.com/VIZ-Blockchain/viz-go-lib/types"
)
//SignedTransaction structure of a signed transaction
type SignedTransaction struct {
*operations.Transaction
}
//NewSignedTransaction initialization of a new signed transaction
func NewSignedTransaction(tx *operations.Transaction) *SignedTransaction {
if tx.Expiration == nil {
expiration := time.Now().Add(30 * time.Second).UTC()
tx.Expiration = &types.Time{Time: &expiration}
}
return &SignedTransaction{tx}
}
//Serialize function serializes a transaction
func (tx *SignedTransaction) Serialize() ([]byte, error) {
var b bytes.Buffer
encoder := transaction.NewEncoder(&b)
if err := encoder.Encode(tx.Transaction); err != nil {
return nil, err
}
return b.Bytes(), nil
}
//Digest function that returns a digest from a serialized transaction
func (tx *SignedTransaction) Digest(chain string) ([]byte, error) {
var msgBuffer bytes.Buffer
// Write the chain ID.
rawChainID, err := hex.DecodeString(chain)
if err != nil {
return nil, fmt.Errorf("failed to decode chain ID: %v \n Error : %w", chain, err)
}
if _, err := msgBuffer.Write(rawChainID); err != nil {
return nil, fmt.Errorf("failed to write chain ID : %w", err)
}
// Write the serialized transaction.
rawTx, err := tx.Serialize()
if err != nil {
return nil, err
}
if _, err := msgBuffer.Write(rawTx); err != nil {
return nil, fmt.Errorf("failed to write serialized transaction : %w", err)
}
// Compute the digest.
digest := sha256.Sum256(msgBuffer.Bytes())
return digest[:], nil
}
//Sign function directly generating transaction signature
func (tx *SignedTransaction) Sign(privKeys [][]byte, chain string) error {
var buf bytes.Buffer
chainid, errdec := hex.DecodeString(chain)
if errdec != nil {
return errdec
}
txRaw, err := tx.Serialize()
if err != nil {
return err
}
buf.Write(chainid)
buf.Write(txRaw)
data := buf.Bytes()
//msg_sha := crypto.Sha256(buf.Bytes())
var sigsHex []string
for _, privB := range privKeys {
sigBytes, err := tx.SignSingle(privB, data)
if err != nil {
return err
}
sigsHex = append(sigsHex, hex.EncodeToString(sigBytes))
}
tx.Transaction.Signatures = sigsHex
return nil
}