/
transaction_user_delegate.go
99 lines (83 loc) · 2.07 KB
/
transaction_user_delegate.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
package types
import (
ethcmn "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/rlp"
"math/big"
"strings"
"sync/atomic"
)
type TxUserDelegate struct {
CreatedAt uint64 // 交易发起时间
Sender PublicKey // 交易发起者公钥
Nonce uint64 // 交易发起者nonce
OpType uint8 // 操作类型 1-抵押选举 2-赎回 3-领取收益
OpValue *big.Int // Op对应的值,OpType=1时为抵押金额
Receiver []byte // 接受者地址 OpType=1时为节点地址
Signature []byte // 交易签名
hash atomic.Value
}
const (
USER_OPTYPE_NULL = uint8(iota)
USER_OPTYPE_MORTGAGE
USER_OPTYPE_REEDEM
USER_OPTYPE_COLLECT
)
func NewUserDelegateTx() *TxUserDelegate {
return &TxUserDelegate{}
}
func (tx *TxUserDelegate) Sign(privkey string) ([]byte, error) {
if strings.HasPrefix(privkey, "0x") {
privkey = string([]byte(privkey)[2:])
}
priv, err := crypto.ToECDSA(ethcmn.Hex2Bytes(privkey))
if err != nil {
return nil, err
}
return crypto.Sign(tx.SigHash().Bytes(), priv)
}
func (tx *TxUserDelegate) Verify() bool {
if len(tx.Signature) != 65 {
return false
}
pubkey, err := crypto.SigToPub(tx.SigHash().Bytes(), tx.Signature)
if err != nil {
return false
}
if crypto.PubkeyToAddress(*pubkey) != tx.Sender.ToAddress().Address {
return false
}
return true
}
func (tx *TxUserDelegate) SigHash() ethcmn.Hash {
message, _ := rlp.EncodeToBytes([]interface{}{
tx.CreatedAt,
tx.Sender,
tx.Nonce,
tx.OpType,
tx.OpValue,
tx.Receiver,
})
return rlpHash(message)
}
func (tx *TxUserDelegate) ToBytes() []byte {
bs, _ := rlp.EncodeToBytes(tx)
return bs
}
func (tx *TxUserDelegate) FromBytes(bs []byte) error {
return rlp.DecodeBytes(bs, tx)
}
func (tx *TxUserDelegate) Hash() ethcmn.Hash {
if hash := tx.hash.Load(); hash != nil {
return hash.(ethcmn.Hash)
}
v := rlpHash(tx)
tx.hash.Store(v)
return v
}
func (tx *TxUserDelegate) Cost() *big.Int {
return big.NewInt(tx.GasWanted())
}
func (tx *TxUserDelegate) GasWanted() int64 {
return TxGas * 100
}