diff --git a/transaction.go b/transaction.go new file mode 100644 index 000000000..fe04ff6e8 --- /dev/null +++ b/transaction.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[:] +} diff --git a/utils.go b/utils.go index 8651f741c..6356ca08c 100644 --- a/utils.go +++ b/utils.go @@ -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 +} diff --git a/utils_test.go b/utils_test.go new file mode 100644 index 000000000..bc7255297 --- /dev/null +++ b/utils_test.go @@ -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") + } + } +}