-
Notifications
You must be signed in to change notification settings - Fork 0
/
transaction.go
48 lines (42 loc) · 980 Bytes
/
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
package blockchain
import (
"bytes"
"crypto/rsa"
)
func NewTransaction(user *User, lasthash []byte, to string, value uint64) *Transaction {
tx := &Transaction{
RandBytes: GenerateRandomBytes(RAND_BYTES),
PrevBlock: lasthash,
Sender: user.Address(),
Receiver: to,
Value: value,
}
if value > START_PERCENT {
tx.ToStorage = STORAGE_REWARD
}
tx.CurrHash = tx.hash()
tx.Signature = tx.sign(user.Private())
return tx
}
func (tx *Transaction) hash() []byte {
return HashSum(bytes.Join(
[][]byte{
tx.RandBytes,
tx.PrevBlock,
[]byte(tx.Sender),
[]byte(tx.Receiver),
ToBytes(tx.Value),
ToBytes(tx.ToStorage),
},
[]byte{},
))
}
func (tx *Transaction) sign(priv *rsa.PrivateKey) []byte {
return Sign(priv, tx.CurrHash)
}
func (tx *Transaction) hashIsValid() bool {
return bytes.Equal(tx.hash(), tx.CurrHash)
}
func (tx *Transaction) signIsValid() bool {
return Verify(ParsePublic(tx.Sender), tx.CurrHash, tx.Signature) == nil
}