-
Notifications
You must be signed in to change notification settings - Fork 670
/
tx.go
64 lines (53 loc) · 1.41 KB
/
tx.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
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package tx
import (
"github.com/ava-labs/avalanchego/cache"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/crypto/secp256k1"
"github.com/ava-labs/avalanchego/utils/hashing"
)
var secpCache = secp256k1.RecoverCache{
LRU: cache.LRU[ids.ID, *secp256k1.PublicKey]{
Size: 2048,
},
}
type Tx struct {
Unsigned `serialize:"true" json:"unsigned"`
Signature [secp256k1.SignatureLen]byte `serialize:"true" json:"signature"`
}
func Parse(bytes []byte) (*Tx, error) {
tx := &Tx{}
_, err := Codec.Unmarshal(bytes, tx)
return tx, err
}
func Sign(utx Unsigned, key *secp256k1.PrivateKey) (*Tx, error) {
unsignedBytes, err := Codec.Marshal(CodecVersion, &utx)
if err != nil {
return nil, err
}
sig, err := key.Sign(unsignedBytes)
if err != nil {
return nil, err
}
tx := &Tx{
Unsigned: utx,
}
copy(tx.Signature[:], sig)
return tx, nil
}
func (tx *Tx) ID() (ids.ID, error) {
bytes, err := Codec.Marshal(CodecVersion, tx)
return hashing.ComputeHash256Array(bytes), err
}
func (tx *Tx) SenderID() (ids.ShortID, error) {
unsignedBytes, err := Codec.Marshal(CodecVersion, &tx.Unsigned)
if err != nil {
return ids.ShortEmpty, err
}
pk, err := secpCache.RecoverPublicKey(unsignedBytes, tx.Signature[:])
if err != nil {
return ids.ShortEmpty, err
}
return pk.Address(), nil
}