Initial commit
This commit is contained in:
43
chain/transaction.go
Normal file
43
chain/transaction.go
Normal file
@@ -0,0 +1,43 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user