wallets
This commit is contained in:
9 files changed
+396
-162
No files matched your search
@@ -15,17 +15,6 @@ type Transaction struct {
|
||||
Outputs []TxOutput
|
||||
}
|
||||
|
||||
type TxOutput struct {
|
||||
Value int
|
||||
PubKey string
|
||||
}
|
||||
|
||||
type TxInput struct {
|
||||
ID []byte
|
||||
Out int
|
||||
Sig string
|
||||
}
|
||||
|
||||
func (tx *Transaction) SetID() {
|
||||
var encoded bytes.Buffer
|
||||
var hash [32]byte
|
||||
@@ -87,11 +76,3 @@ func NewTransaction(from, to string, amount int, chain *BlockChain) *Transaction
|
||||
func (tx *Transaction) IsCoinbase() bool {
|
||||
return len(tx.Inputs) == 1 && len(tx.Inputs[0].ID) == 0 && tx.Inputs[0].Out == -1
|
||||
}
|
||||
|
||||
func (in *TxInput) CanUnlock(data string) bool {
|
||||
return in.Sig == data
|
||||
}
|
||||
|
||||
func (out *TxOutput) CanBeUnlocked(data string) bool {
|
||||
return out.PubKey == data
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package blockchain
|
||||
|
||||
type TxOutput struct {
|
||||
Value int
|
||||
PubKey string
|
||||
}
|
||||
|
||||
type TxInput struct {
|
||||
ID []byte
|
||||
Out int
|
||||
Sig string
|
||||
}
|
||||
|
||||
func (in *TxInput) CanUnlock(data string) bool {
|
||||
return in.Sig == data
|
||||
}
|
||||
|
||||
func (out *TxOutput) CanBeUnlocked(data string) bool {
|
||||
return out.PubKey == data
|
||||
}
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"strconv"
|
||||
|
||||
"github.com/SowinskiBraeden/golang-blockchain/blockchain"
|
||||
"github.com/SowinskiBraeden/golang-blockchain/wallet"
|
||||
)
|
||||
|
||||
type CommandLine struct{}
|
||||
|
||||
func (cli *CommandLine) printUsage() {
|
||||
fmt.Println("Usage:")
|
||||
fmt.Println(" getbalance -address ADDRESS - get the balance for an address")
|
||||
fmt.Println(" createblockchain -address ADDRESS create a blockchain")
|
||||
fmt.Println(" printchain - Prints the blocks in the chain")
|
||||
fmt.Println(" send -from FROM -to TO -amount AMOUNT - Send amount to an address")
|
||||
fmt.Println(" createwallet - CReates a new Wallet")
|
||||
fmt.Println(" listaddresses - Lists the addresses in our wallet file")
|
||||
}
|
||||
|
||||
func (cli *CommandLine) validateArgs() {
|
||||
if len(os.Args) < 2 {
|
||||
cli.printUsage()
|
||||
runtime.Goexit()
|
||||
}
|
||||
}
|
||||
|
||||
func (cli *CommandLine) listAddresses() {
|
||||
wallets, _ := wallet.CreateWallets()
|
||||
addresses := wallets.GetAllAddresses()
|
||||
|
||||
for _, address := range addresses {
|
||||
fmt.Println(address)
|
||||
}
|
||||
}
|
||||
|
||||
func (cli *CommandLine) createWallet() {
|
||||
wallets, _ := wallet.CreateWallets()
|
||||
address := wallets.AddWallet()
|
||||
wallets.SaveFile()
|
||||
|
||||
fmt.Printf("New address is: %s\n", address)
|
||||
}
|
||||
|
||||
func (cli *CommandLine) printChain() {
|
||||
chain := blockchain.ContinueBlockChain("")
|
||||
defer chain.Database.Close()
|
||||
iter := chain.Iterator()
|
||||
|
||||
for {
|
||||
block := iter.Next()
|
||||
|
||||
fmt.Printf("Prev. Hash: %x\n", block.PrevHash)
|
||||
fmt.Printf("Hash: %x\n", block.Hash)
|
||||
pow := blockchain.NewProof(block)
|
||||
fmt.Printf("PoW: %s\n", strconv.FormatBool(pow.Validate()))
|
||||
fmt.Println()
|
||||
|
||||
if len(block.PrevHash) == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (cli *CommandLine) createBlockChain(address string) {
|
||||
chain := blockchain.InitBlockChain(address)
|
||||
chain.Database.Close()
|
||||
fmt.Println("Finished!")
|
||||
}
|
||||
|
||||
func (cli *CommandLine) getBalance(address string) {
|
||||
chain := blockchain.ContinueBlockChain(address)
|
||||
defer chain.Database.Close()
|
||||
|
||||
balance := 0
|
||||
UTXOs := chain.FindUTXO(address)
|
||||
|
||||
for _, out := range UTXOs {
|
||||
balance += out.Value
|
||||
}
|
||||
|
||||
fmt.Printf("Balance of %s: %d\n", address, balance)
|
||||
}
|
||||
|
||||
func (cli *CommandLine) send(from, to string, amount int) {
|
||||
chain := blockchain.ContinueBlockChain(from)
|
||||
defer chain.Database.Close()
|
||||
|
||||
tx := blockchain.NewTransaction(from, to, amount, chain)
|
||||
chain.AddBlock([]*blockchain.Transaction{tx})
|
||||
fmt.Println("Success!")
|
||||
}
|
||||
|
||||
func (cli *CommandLine) Run() {
|
||||
cli.validateArgs()
|
||||
|
||||
getBalanceCmd := flag.NewFlagSet("getbalance", flag.ExitOnError)
|
||||
createBlockchainCmd := flag.NewFlagSet("createblockchain", flag.ExitOnError)
|
||||
sendCmd := flag.NewFlagSet("send", flag.ExitOnError)
|
||||
printChainCmd := flag.NewFlagSet("printchain", flag.ExitOnError)
|
||||
createWalletCmd := flag.NewFlagSet("createwallet", flag.ExitOnError)
|
||||
listAddressesCmd := flag.NewFlagSet("listaddresses", flag.ExitOnError)
|
||||
|
||||
getBalanceAddress := getBalanceCmd.String("address", "", "The address to get balance of")
|
||||
createBlockchainAddress := createBlockchainCmd.String("address", "", "The address to create a blockchain for")
|
||||
sendFrom := sendCmd.String("from", "", "Source wallet address")
|
||||
sendTo := sendCmd.String("to", "", "Destination wallet address")
|
||||
sendAmount := sendCmd.Int("amount", 0, "Amount to send")
|
||||
|
||||
switch os.Args[1] {
|
||||
case "getbalance":
|
||||
err := getBalanceCmd.Parse(os.Args[2:])
|
||||
blockchain.Handle(err)
|
||||
|
||||
case "createblockchain":
|
||||
err := createBlockchainCmd.Parse(os.Args[2:])
|
||||
blockchain.Handle(err)
|
||||
|
||||
case "listaddresses":
|
||||
err := listAddressesCmd.Parse(os.Args[2:])
|
||||
blockchain.Handle(err)
|
||||
|
||||
case "createwallet":
|
||||
err := createWalletCmd.Parse(os.Args[2:])
|
||||
blockchain.Handle(err)
|
||||
|
||||
case "printchain":
|
||||
err := printChainCmd.Parse(os.Args[2:])
|
||||
blockchain.Handle(err)
|
||||
|
||||
case "send":
|
||||
err := sendCmd.Parse(os.Args[4:])
|
||||
blockchain.Handle(err)
|
||||
|
||||
default:
|
||||
cli.printUsage()
|
||||
runtime.Goexit()
|
||||
}
|
||||
|
||||
if getBalanceCmd.Parsed() {
|
||||
if *getBalanceAddress == "" {
|
||||
getBalanceCmd.Usage()
|
||||
runtime.Goexit()
|
||||
}
|
||||
cli.getBalance(*getBalanceAddress)
|
||||
}
|
||||
|
||||
if createBlockchainCmd.Parsed() {
|
||||
if *createBlockchainAddress == "" {
|
||||
createBlockchainCmd.Usage()
|
||||
runtime.Goexit()
|
||||
}
|
||||
cli.createBlockChain(*createBlockchainAddress)
|
||||
}
|
||||
|
||||
if listAddressesCmd.Parsed() {
|
||||
cli.listAddresses()
|
||||
}
|
||||
|
||||
if createWalletCmd.Parsed() {
|
||||
cli.createWallet()
|
||||
}
|
||||
|
||||
if printChainCmd.Parsed() {
|
||||
cli.printChain()
|
||||
}
|
||||
|
||||
if sendCmd.Parsed() {
|
||||
if *sendFrom == "" || *sendTo == "" || *sendAmount == 0 {
|
||||
sendCmd.Usage()
|
||||
runtime.Goexit()
|
||||
}
|
||||
cli.send(*sendFrom, *sendTo, *sendAmount)
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,10 @@ module github.com/SowinskiBraeden/golang-blockchain
|
||||
|
||||
go 1.19
|
||||
|
||||
require github.com/dgraph-io/badger v1.6.2
|
||||
require (
|
||||
github.com/dgraph-io/badger v1.6.2
|
||||
github.com/mr-tron/base58 v1.2.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96 // indirect
|
||||
@@ -11,6 +14,6 @@ require (
|
||||
github.com/dustin/go-humanize v1.0.0 // indirect
|
||||
github.com/golang/protobuf v1.3.1 // indirect
|
||||
github.com/pkg/errors v0.8.1 // indirect
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859 // indirect
|
||||
golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb // indirect
|
||||
golang.org/x/net v0.3.0 // indirect
|
||||
golang.org/x/sys v0.3.0 // indirect
|
||||
)
|
||||
@@ -32,6 +32,8 @@ github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
|
||||
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
|
||||
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
|
||||
github.com/mr-tron/base58 v1.2.0 h1:T/HDJBh4ZCPbU39/+c3rRvE0uKBQlU27+QI8LJ4t64o=
|
||||
github.com/mr-tron/base58 v1.2.0/go.mod h1:BinMc/sQntlIE1frQmRFPUoPA1Zkr8VRgBdjWI2mNwc=
|
||||
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
|
||||
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
@@ -55,12 +57,14 @@ github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljT
|
||||
github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
|
||||
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI=
|
||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/net v0.3.0 h1:VWL6FNY2bEEmsGVKabSlHu5Irp34xmMRoqb/9lF9lxk=
|
||||
golang.org/x/net v0.3.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE=
|
||||
golang.org/x/sys v0.0.0-20181205085412-a5c9d58dba9a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb h1:fgwFCsaw9buMuxNd6+DQfAuSFqbNiQZpcgJQAgJsK6k=
|
||||
golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.3.0 h1:w8ZOecv6NaNa/zC8944JTU3vz4u6Lagfk4RPQxv92NQ=
|
||||
golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
|
||||
@@ -1,148 +1,13 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"strconv"
|
||||
|
||||
"github.com/SowinskiBraeden/golang-blockchain/blockchain"
|
||||
"github.com/SowinskiBraeden/golang-blockchain/cli"
|
||||
)
|
||||
|
||||
type CommandLine struct{}
|
||||
|
||||
func (cli *CommandLine) printUsage() {
|
||||
fmt.Println("Usage:")
|
||||
fmt.Println(" getbalance -address ADDRESS - get the balance for an address")
|
||||
fmt.Println(" createblockchain -address ADDRESS create a blockchain")
|
||||
fmt.Println(" printchain - Prints the blocks in the chain")
|
||||
fmt.Println(" send -from FROM -to TO -amount AMOUNT - Send amount to an address")
|
||||
}
|
||||
|
||||
func (cli *CommandLine) validateArgs() {
|
||||
if len(os.Args) < 2 {
|
||||
cli.printUsage()
|
||||
runtime.Goexit()
|
||||
}
|
||||
}
|
||||
|
||||
func (cli *CommandLine) printChain() {
|
||||
chain := blockchain.ContinueBlockChain("")
|
||||
defer chain.Database.Close()
|
||||
iter := chain.Iterator()
|
||||
|
||||
for {
|
||||
block := iter.Next()
|
||||
|
||||
fmt.Printf("Prev. Hash: %x\n", block.PrevHash)
|
||||
fmt.Printf("Hash: %x\n", block.Hash)
|
||||
pow := blockchain.NewProof(block)
|
||||
fmt.Printf("PoW: %s\n", strconv.FormatBool(pow.Validate()))
|
||||
fmt.Println()
|
||||
|
||||
if len(block.PrevHash) == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (cli *CommandLine) createBlockChain(address string) {
|
||||
chain := blockchain.InitBlockChain(address)
|
||||
chain.Database.Close()
|
||||
fmt.Println("Finished!")
|
||||
}
|
||||
|
||||
func (cli *CommandLine) getBalance(address string) {
|
||||
chain := blockchain.ContinueBlockChain(address)
|
||||
defer chain.Database.Close()
|
||||
|
||||
balance := 0
|
||||
UTXOs := chain.FindUTXO(address)
|
||||
|
||||
for _, out := range UTXOs {
|
||||
balance += out.Value
|
||||
}
|
||||
|
||||
fmt.Printf("Balance of %s: %d\n", address, balance)
|
||||
}
|
||||
|
||||
func (cli *CommandLine) send(from, to string, amount int) {
|
||||
chain := blockchain.ContinueBlockChain(from)
|
||||
defer chain.Database.Close()
|
||||
|
||||
tx := blockchain.NewTransaction(from, to, amount, chain)
|
||||
chain.AddBlock([]*blockchain.Transaction{tx})
|
||||
fmt.Println("Success!")
|
||||
}
|
||||
|
||||
func (cli *CommandLine) run() {
|
||||
cli.validateArgs()
|
||||
|
||||
getBalanceCmd := flag.NewFlagSet("getbalance", flag.ExitOnError)
|
||||
createBlockchainCmd := flag.NewFlagSet("createblockchain", flag.ExitOnError)
|
||||
sendCmd := flag.NewFlagSet("send", flag.ExitOnError)
|
||||
printChainCmd := flag.NewFlagSet("printchain", flag.ExitOnError)
|
||||
|
||||
getBalanceAddress := getBalanceCmd.String("address", "", "The address to get balance of")
|
||||
createBlockchainAddress := createBlockchainCmd.String("address", "", "The address to create a blockchain for")
|
||||
sendFrom := sendCmd.String("from", "", "Source wallet address")
|
||||
sendTo := sendCmd.String("to", "", "Destination wallet address")
|
||||
sendAmount := sendCmd.Int("amount", 0, "Amount to send")
|
||||
|
||||
switch os.Args[1] {
|
||||
case "getbalance":
|
||||
err := getBalanceCmd.Parse(os.Args[2:])
|
||||
blockchain.Handle(err)
|
||||
|
||||
case "createblockchain":
|
||||
err := createBlockchainCmd.Parse(os.Args[2:])
|
||||
blockchain.Handle(err)
|
||||
|
||||
case "printchain":
|
||||
err := printChainCmd.Parse(os.Args[2:])
|
||||
blockchain.Handle(err)
|
||||
|
||||
case "send":
|
||||
err := sendCmd.Parse(os.Args[4:])
|
||||
blockchain.Handle(err)
|
||||
|
||||
default:
|
||||
cli.printUsage()
|
||||
runtime.Goexit()
|
||||
}
|
||||
|
||||
if getBalanceCmd.Parsed() {
|
||||
if *getBalanceAddress == "" {
|
||||
getBalanceCmd.Usage()
|
||||
runtime.Goexit()
|
||||
}
|
||||
cli.getBalance(*getBalanceAddress)
|
||||
}
|
||||
|
||||
if createBlockchainCmd.Parsed() {
|
||||
if *createBlockchainAddress == "" {
|
||||
createBlockchainCmd.Usage()
|
||||
runtime.Goexit()
|
||||
}
|
||||
cli.createBlockChain(*createBlockchainAddress)
|
||||
}
|
||||
|
||||
if printChainCmd.Parsed() {
|
||||
cli.printChain()
|
||||
}
|
||||
|
||||
if sendCmd.Parsed() {
|
||||
if *sendFrom == "" || *sendTo == "" || *sendAmount == 0 {
|
||||
sendCmd.Usage()
|
||||
runtime.Goexit()
|
||||
}
|
||||
cli.send(*sendFrom, *sendTo, *sendAmount)
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
defer os.Exit(0)
|
||||
cli := CommandLine{}
|
||||
cli.run()
|
||||
cmd := cli.CommandLine{}
|
||||
cmd.Run()
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package wallet
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/mr-tron/base58"
|
||||
)
|
||||
|
||||
func Base58Encode(input []byte) []byte {
|
||||
encode := base58.Encode(input)
|
||||
|
||||
return []byte(encode)
|
||||
}
|
||||
|
||||
func Base58Decode(input []byte) []byte {
|
||||
decode, err := base58.Decode(string(input[:]))
|
||||
if err != nil {
|
||||
log.Panic(err)
|
||||
}
|
||||
|
||||
return decode
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package wallet
|
||||
|
||||
import (
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"log"
|
||||
)
|
||||
|
||||
const (
|
||||
checksumLength = 4
|
||||
version = byte(0x00)
|
||||
)
|
||||
|
||||
type Wallet struct {
|
||||
PrivateKey ecdsa.PrivateKey
|
||||
PublicKey []byte
|
||||
}
|
||||
|
||||
func (w Wallet) Address() []byte {
|
||||
pubHash := PublicKeyHash(w.PublicKey)
|
||||
|
||||
versionedHash := append([]byte{version}, pubHash...)
|
||||
checksum := CheckSum(versionedHash)
|
||||
|
||||
fullHash := append(versionedHash, checksum...)
|
||||
address := Base58Encode(fullHash)
|
||||
|
||||
return address
|
||||
}
|
||||
|
||||
func NewKeyPair() (ecdsa.PrivateKey, []byte) {
|
||||
curve := elliptic.P256()
|
||||
|
||||
private, err := ecdsa.GenerateKey(curve, rand.Reader)
|
||||
if err != nil {
|
||||
log.Panic(err)
|
||||
}
|
||||
|
||||
pub := append(private.PublicKey.X.Bytes(), private.PublicKey.Y.Bytes()...)
|
||||
return *private, pub
|
||||
}
|
||||
|
||||
func MakeWallet() *Wallet {
|
||||
private, public := NewKeyPair()
|
||||
wallet := Wallet{private, public}
|
||||
|
||||
return &wallet
|
||||
}
|
||||
|
||||
func PublicKeyHash(pubKey []byte) []byte {
|
||||
pubHash := sha256.Sum256(pubKey)
|
||||
|
||||
hasher := sha256.New()
|
||||
_, err := hasher.Write(pubHash[:])
|
||||
if err != nil {
|
||||
log.Panic(err)
|
||||
}
|
||||
|
||||
publicRipMD := hasher.Sum(nil)
|
||||
|
||||
return publicRipMD
|
||||
}
|
||||
|
||||
func CheckSum(payload []byte) []byte {
|
||||
firstHash := sha256.Sum256(payload)
|
||||
secondHash := sha256.Sum256(firstHash[:])
|
||||
|
||||
return secondHash[:checksumLength]
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package wallet
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/elliptic"
|
||||
"encoding/gob"
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
const walletFile = "./tmp/wallets.data"
|
||||
|
||||
type Wallets struct {
|
||||
Wallets map[string]*Wallet
|
||||
}
|
||||
|
||||
func CreateWallets() (*Wallets, error) {
|
||||
wallets := Wallets{}
|
||||
wallets.Wallets = make(map[string]*Wallet)
|
||||
|
||||
err := wallets.LoadFile()
|
||||
|
||||
return &wallets, err
|
||||
}
|
||||
|
||||
func (ws *Wallets) AddWallet() string {
|
||||
wallet := MakeWallet()
|
||||
address := string(wallet.Address())
|
||||
|
||||
ws.Wallets[address] = wallet
|
||||
|
||||
return address
|
||||
}
|
||||
|
||||
func (ws *Wallets) GetAllAddresses() []string {
|
||||
var addresses []string
|
||||
|
||||
for address := range ws.Wallets {
|
||||
addresses = append(addresses, address)
|
||||
}
|
||||
|
||||
return addresses
|
||||
}
|
||||
|
||||
func (ws Wallets) GetWallet(address string) Wallet {
|
||||
return *ws.Wallets[address]
|
||||
}
|
||||
|
||||
func (ws *Wallets) LoadFile() error {
|
||||
if _, err := os.Stat(walletFile); os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
|
||||
var wallets Wallets
|
||||
|
||||
fileContent, err := os.ReadFile(walletFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
gob.Register(elliptic.P256())
|
||||
decoder := gob.NewDecoder(bytes.NewReader(fileContent))
|
||||
err = decoder.Decode(&wallets)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ws.Wallets = wallets.Wallets
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ws *Wallets) SaveFile() {
|
||||
var content bytes.Buffer
|
||||
|
||||
gob.Register(elliptic.P256())
|
||||
|
||||
encoder := gob.NewEncoder(&content)
|
||||
err := encoder.Encode(ws)
|
||||
if err != nil {
|
||||
log.Panic(err)
|
||||
}
|
||||
|
||||
err = os.WriteFile(walletFile, content.Bytes(), 0644)
|
||||
if err != nil {
|
||||
log.Panic(err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user