Files
monoblock/chain/transaction.go
2022-04-22 18:11:33 +02:00

49 lines
1.0 KiB
Go

package chain
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"encoding/gob"
"time"
)
type transaction struct {
Src string
Dst string
Amount int
Timestamp int64
}
func NewTransaction(source string, dst string, amount int) transaction {
return transaction{Src: source, Dst: dst, Amount: amount, Timestamp: time.Now().Unix()}
}
func (ta transaction) SignTransaction(privKey *rsa.PrivateKey, d int) ([]byte, error) {
return rsa.SignPKCS1v15(rand.Reader, privKey, crypto.SHA256, ta.HashTransaction())
}
func (ta transaction) HashTransaction() []byte {
var buf bytes.Buffer
gob.NewEncoder(&buf).Encode(ta)
hash := sha256.New().Sum(buf.Bytes())
return hash
}
func (ta transaction) ToBytes() []byte {
bytes := []byte(ta.Src)
bytes = append(bytes, []byte(ta.Dst)...)
bytes = append(bytes, byte(ta.Amount))
//bytes = append(bytes, []byte(ta.Timestamp))
return bytes
}
func (ta transaction) ToBytesSerialize() []byte {
var buf bytes.Buffer
gob.NewEncoder(&buf).Encode(ta)
return buf.Bytes()
}