micw/common/tx_test.go

75 lines
2.1 KiB
Go
Raw Permalink Normal View History

2024-11-17 21:24:19 +00:00
package common
import (
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
"testing"
"time"
)
func TestNewTx(t *testing.T) {
senderPublicKey, senderPrivateKey, err := ed25519.GenerateKey(nil)
if err != nil {
t.Fatalf("failed to generate key pair: %s", err.Error())
}
_, receiverPublicKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatalf("failed to generate key pair: %s", err.Error())
}
newTxOpts := MakeNewTxOpts(
senderPublicKey, senderPrivateKey, receiverPublicKey,
0.01, "", false)
newTxOptsJson, err := newTxOpts.ToJSON(EncodingRawUrl)
if err != nil {
t.Fatalf("failed to marshal JSON to tx: %s", err.Error())
}
newTxOptsFromJSON, err := NewTxOptsFromJSON(newTxOptsJson)
if err != nil {
t.Fatalf("failed to unmarshal tx from JSON: %s", err.Error())
}
if ok := newTxOptsFromJSON.ValidateBlockId(); !ok {
t.Fatalf("invalid block id")
}
if ok := newTxOptsFromJSON.ValidateHash(); !ok {
t.Fatalf("invalid hash. Got hash: %s", base64.RawURLEncoding.EncodeToString(newTxOptsFromJSON.Hash))
}
if ok := newTxOptsFromJSON.ValidateSignature(); !ok {
t.Fatalf("invalid signature")
}
}
func TestTx(t *testing.T) {
senderPublicKey, senderPrivateKey, err := ed25519.GenerateKey(nil)
if err != nil {
t.Fatalf("failed to generate key pair: %s", err.Error())
}
_, receiverPublicKey, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
t.Fatalf("failed to generate key pair: %s", err.Error())
}
newTxOpts := MakeNewTxOpts(
senderPublicKey, senderPrivateKey, receiverPublicKey,
0.01, "", false)
tx, _ := newTxOpts.Process(false, time.Time{})
txJson, err := tx.ToJSON(EncodingRawUrl)
if err != nil {
t.Fatalf("failed to marshal JSON to tx: %s", err.Error())
}
txFromJson, err := TxFromJSON(txJson)
if err != nil {
t.Fatalf("failed to unmarshal tx from JSON: %s", err.Error())
}
if ok := txFromJson.ValidateBlockId(); !ok {
t.Fatalf("invalid block id")
}
if ok := txFromJson.ValidateHash(); !ok {
t.Fatalf("invalid hash. Got hash: %s", base64.RawURLEncoding.EncodeToString(txFromJson.Hash))
}
if ok := txFromJson.ValidateSignature(); !ok {
t.Fatalf("invalid signature")
}
}