add transaction, utils, utils_test.

pull/2/head
Minh Doan 6 years ago
parent c0fd09be05
commit 212c86a784
  1. 48
      transaction.go
  2. 31
      utils.go
  3. 25
      utils_test.go

@ -0,0 +1,48 @@
package main
import (
"bytes"
"crypto/sha256"
"encoding/gob"
"log"
"strconv"
"strings"
)
// Transaction represents a Bitcoin transaction
type Transaction struct {
ID []byte
inputAddresss []string
outputAddress []string
value []int
}
func (tx *Transaction) Parse(data string) {
items := strings.Split(data, ",")
for _, value := range items {
pair := strings.Split(value, " ")
if len(pair) == 3 {
intValue, err := strconv.Atoi(pair[2])
if err != nil {
tx.inputAddress = append(tx.inputAddresss, strings.Trim(pair[0]))
tx.outputAddress = append(tx.outputAddress, strings.Trim(pair[1]))
tx.value = append(tx.value, intValue)
}
}
}
return res
}
// SetID sets ID of a transaction
func (tx *Transaction) SetID() {
var encoded bytes.Buffer
var hash [32]byte
enc := gob.NewEncoder(&encoded)
err := enc.Encode(tx)
if err != nil {
log.Panic(err)
}
hash = sha256.Sum256(encoded.Bytes())
tx.ID = hash[:]
}

@ -5,6 +5,8 @@ import (
"encoding/binary"
"encoding/gob"
"log"
"strconv"
"strings"
)
// IntToHex converts an int64 to a byte array
@ -37,3 +39,32 @@ func DeserializeBlock(d []byte) *Block {
return &block
}
// Helper library to convert '1,2,3,4' into []int{1,2,3,4}.
func ConvertIntoInts(data string) []int {
var res = []int{}
items := strings.Split(data, " ")
for _, value := range items {
intValue, err := strconv.Atoi(value)
checkError(err)
res = append(res, intValue)
}
return res
}
// Helper library to convert '1,2,3,4' into []int{1,2,3,4}.
func ConvertIntoMap(data string) map[string]int {
var res = map[string]int
items := strings.Split(data, ",")
for _, value := range items {
pair := strings.Split(value, " ")
if len(pair) == 3 {
intValue, err := strconv.Atoi(pair[2])
if err != nil {
pair[0] = strings.Trim(pair[0])
res[pair[0]] = intValue
}
}
}
return res
}

@ -0,0 +1,25 @@
package main
import "testing"
func TestConvertIntoMap(t *testing.T) {
data := "minh:3,mike:2"
res := ConvertIntoMap(data)
if len(res) != 2 {
t.Errorf("Result should have 2 pairs (key, value)")
}
if val, ok := res["minh"]; !ok {
t.Errorf("Result should contain key minh")
} else {
if res["minh"] != 3 {
t.Errorf("Value of minh should be 3")
}
}
if val, ok := res["mike"]; !ok {
t.Errorf("Result should contain key mike")
} else {
if res["minh"] != 3 {
t.Errorf("Value of minh should be 2")
}
}
}
Loading…
Cancel
Save