Files
monoblock/chain/transaction.go
2022-04-20 22:04:53 +02:00

44 lines
959 B
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 time.Time
}
func NewTransaction(source string, dst string, amount int) transaction {
return transaction{Src: source, Dst: dst, Amount: amount, Timestamp: time.Now()}
}
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)...)
//fmt.Printf("%s", ta.Dst)
bytes = append(bytes, byte(ta.Amount))
bytes = append(bytes, []byte(ta.Timestamp.String())...)
return bytes
}