diff --git a/.github/workflows/build_go.yml b/.github/workflows/build_go.yml index 4d990cf..0e0c83f 100644 --- a/.github/workflows/build_go.yml +++ b/.github/workflows/build_go.yml @@ -23,3 +23,7 @@ jobs: - name: Test run: go test -v ./... + + - name: Run golangci-lint + uses: golangci/golangci-lint-action@v3.2.0 + diff --git a/.github/workflows/coverage_go.yml b/.github/workflows/coverage_go.yml new file mode 100644 index 0000000..ca74f75 --- /dev/null +++ b/.github/workflows/coverage_go.yml @@ -0,0 +1,58 @@ +on: + pull_request: + branches: + - main + +jobs: + test: + runs-on: ubuntu-latest + name: Update coverage badge + steps: + - name: Checkout + uses: actions/checkout@v2 + with: + persist-credentials: false # otherwise, the token used is the GITHUB_TOKEN, instead of your personal access token. + fetch-depth: 0 # otherwise, there would be errors pushing refs to the destination repository. + + - name: Setup go + uses: actions/setup-go@v2 + with: + go-version: '1.14.4' + + - uses: actions/cache@v2 + with: + path: ~/go/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + + - name: Run Test + run: | + go test -v ./... -covermode=count -coverprofile=coverage.out + go tool cover -func=coverage.out -o=coverage.out + + - name: Go Coverage Badge # Pass the `coverage.out` output to this action + uses: tj-actions/coverage-badge-go@v1.2 + with: + filename: coverage.out + + - name: Verify Changed files + uses: tj-actions/verify-changed-files@v9.1 + id: verify-changed-files + with: + files: README.md + + - name: Commit changes + if: steps.verify-changed-files.outputs.files_changed == 'true' + run: | + git config --local user.email "action@github.com" + git config --local user.name "GitHub Action" + git add README.md + git commit -m "chore: Updated coverage badge." + + - name: Push changes + if: steps.verify-changed-files.outputs.files_changed == 'true' + uses: ad-m/github-push-action@master + with: + github_token: ${{ github.token }} + branch: ${{ github.head_ref }} \ No newline at end of file diff --git a/.gitignore b/.gitignore index 66fd13c..e1f8056 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,12 @@ +# Logs +logs.txt + +# Temporary files +tmp/* + +# VSCode +.vscode/* + # Binaries for programs and plugins *.exe *.exe~ diff --git a/blockchain/block.go b/blockchain/block.go new file mode 100644 index 0000000..9b6dbb2 --- /dev/null +++ b/blockchain/block.go @@ -0,0 +1,91 @@ +package blockchain + +import ( + "bytes" + "crypto/sha256" + "encoding/gob" + "encoding/json" + "strconv" + "strings" + + logging "github.com/MVRetailManager/MVInventoryChain/logging" +) + +type Block struct { + Index int + UnixTimeStamp int64 + Hash []byte + PreviousHash []byte + Nonce int + Difficulty int + Transaction []*Transaction +} + +func NewBlock(index int, unixTimeStamp int64, previousHash []byte, transaction []*Transaction) *Block { + b := &Block{ + Index: index, + UnixTimeStamp: unixTimeStamp, + Hash: make([]byte, 32), + PreviousHash: previousHash, + Nonce: 0, + Difficulty: 1, + Transaction: transaction, + } + + logging.BlocksLogger.Printf("Block Initialised: %v\n", b) + + b.Mine() + + return b +} + +func (b *Block) Mine() { + for !b.validateHash(b.calculateHash()) { + b.Nonce++ + b.Hash = b.calculateHash() + } + + logging.BlocksLogger.Printf("Block Mined:\n Nonce: %v\nHash: %v\n", b.Nonce, b.Hash) +} + +func (b *Block) calculateHash() []byte { + hash := sha256.Sum256([]byte(strconv.Itoa(b.Index) + strconv.FormatInt(b.UnixTimeStamp, 10) + string(b.PreviousHash) + strconv.Itoa(b.Nonce) + strconv.Itoa(b.Difficulty) + transactionToString(b.Transaction))) + return hash[:] +} + +func (b *Block) validateHash(hash []byte) bool { + prefix := strings.Repeat("0", b.Difficulty) + return strings.HasPrefix(string(hash), prefix) +} + +func first(n []byte, _ error) []byte { + return n +} + +func transactionToString(transaction []*Transaction) string { + return string(first(json.Marshal(transaction))) +} + +func (bc *Block) Serialize() []byte { + var res bytes.Buffer + + encoder := gob.NewEncoder(&res) + + err := encoder.Encode(bc) + + HandleError(err) + + return res.Bytes() +} + +func Deserialize(data []byte) *Block { + var block Block + + decoder := gob.NewDecoder(bytes.NewReader(data)) + + err := decoder.Decode(&block) + + HandleError(err) + + return &block +} diff --git a/blockchain/blockchain.go b/blockchain/blockchain.go new file mode 100644 index 0000000..d62c5f3 --- /dev/null +++ b/blockchain/blockchain.go @@ -0,0 +1,312 @@ +package blockchain + +import ( + "bytes" + "crypto/ecdsa" + "encoding/hex" + "fmt" + "os" + "runtime" + "time" + + "github.com/dgraph-io/badger" + + logging "github.com/MVRetailManager/MVInventoryChain/logging" +) + +const ( + dbPath = "./tmp/blockchain" + dbFile = "./tmp/blockchain/MANIFEST" + genesisData = "Genesis Block" +) + +type Blockchain struct { + LastHash []byte + Database *badger.DB +} + +type BlockchainIterator struct { + CurrentHash []byte + Database *badger.DB +} + +func (bc *Blockchain) InitBlockchain(address string) { + var genesis Block + + if DBexists() { + fmt.Println("Blockchain already exists") + runtime.Goexit() + } + + opts := InitDBOpts() + + db, err := badger.Open(opts) + HandleError(err) + + err = db.Update(func(txn *badger.Txn) error { + cbtx := CoinbaseTx(address, genesisData) + genesis = initGenesis([]*Transaction{cbtx}) + err = txn.Set(genesis.Hash, genesis.Serialize()) + HandleError(err) + err = txn.Set([]byte("lh"), genesis.Hash) + + bc.LastHash = genesis.Hash + + return err + }) + + HandleError(err) + + bc.Database = db + + logging.InfoLogger.Printf("New blockchain created with genesis block: %s", genesis.Hash) +} + +func DBexists() bool { + _, err := os.Stat(dbFile) + + return err == nil +} + +func (bc *Blockchain) ContinueBlockchain(address string) { + if !DBexists() { + fmt.Println("No existing blockchain found, please create one.") + runtime.Goexit() + } + + opts := InitDBOpts() + + db, err := badger.Open(opts) + HandleError(err) + + err = db.Update(func(txn *badger.Txn) error { + item, err := txn.Get([]byte("lh")) + HandleError(err) + + err = item.Value(func(val []byte) error { + bc.LastHash = val + return nil + }) + + return err + }) + HandleError(err) + + bc.Database = db +} + +func (bc *Blockchain) FindUnspentTxs(publicKeyHash []byte) []Transaction { + var unspentTxs []Transaction + + spentTXOs := make(map[string][]int) + + iter := bc.Iterator() + + for { + block, err := iter.Next() + HandleError(err) + + for _, tx := range block.Transaction { + txID := hex.EncodeToString(tx.ID) + + Outputs: + for outIdx, out := range tx.Outputs { + if spentTXOs[txID] != nil { + for _, spentOut := range spentTXOs[txID] { + if spentOut == outIdx { + continue Outputs + } + } + } + if out.IsLockedWithkey(publicKeyHash) { + unspentTxs = append(unspentTxs, *tx) + } + } + if !tx.IsCoinbase() { + for _, in := range tx.Inputs { + if in.UsesKey(publicKeyHash) { + inTxID := hex.EncodeToString(in.ID) + spentTXOs[inTxID] = append(spentTXOs[inTxID], in.OutputIndex) + } + } + } + } + + if len(block.PreviousHash) == 0 { + break + } + } + + return unspentTxs +} + +func (bc *Blockchain) HandleUnspentTxs(publicKeyHash []byte) []TxOutput { + var unspentTxs []TxOutput + + unspentTransactions := bc.FindUnspentTxs(publicKeyHash) + + for _, tx := range unspentTransactions { + for _, out := range tx.Outputs { + if out.IsLockedWithkey(publicKeyHash) { + unspentTxs = append(unspentTxs, out) + } + } + } + + return unspentTxs +} + +func (bc *Blockchain) FindSpendableOutputs(publicKeyHash []byte, amount int) (int, map[string][]int) { + unspentOuts := make(map[string][]int) + unspentTxs := bc.FindUnspentTxs(publicKeyHash) + acc := 0 + +Work: + for _, tx := range unspentTxs { + txID := hex.EncodeToString(tx.ID) + + for outIdx, out := range tx.Outputs { + if out.IsLockedWithkey(publicKeyHash) && acc < amount { + acc = out.Value + unspentOuts[txID] = append(unspentOuts[txID], outIdx) + + if acc >= amount { + break Work + } + } + } + } + + return acc, unspentOuts +} + +func InitDBOpts() badger.Options { + opts := badger.DefaultOptions(dbPath) + opts.Dir = dbPath + opts.ValueDir = dbPath + opts.Logger = nil + + return opts +} + +func (bc *Blockchain) AddBlock(block Block) { + err := bc.Database.View(func(txn *badger.Txn) error { + item, err := txn.Get([]byte("lh")) + HandleError(err) + err = item.Value(func(val []byte) error { + bc.LastHash = val + return nil + }) + + return err + }) + HandleError(err) + + nbIndex, _ := bc.Database.Size() + newBlock := NewBlock(int(nbIndex), time.Now().UnixNano(), bc.LastHash, block.Transaction) + + err = bc.Database.Update(func(txn *badger.Txn) error { + err := txn.Set(newBlock.Hash, newBlock.Serialize()) + HandleError(err) + err = txn.Set([]byte("lh"), newBlock.Hash) + + bc.LastHash = newBlock.Hash + + return err + }) + + HandleError(err) +} + +func (bc *Blockchain) Iterator() *BlockchainIterator { + iter := &BlockchainIterator{bc.LastHash, bc.Database} + + return iter +} + +func (iter *BlockchainIterator) Next() (*Block, error) { + var block *Block + var encodedBlock []byte + + err := iter.Database.View(func(txn *badger.Txn) error { + item, err := txn.Get(iter.CurrentHash) + + if err != nil { + HandleError(err) + return err + } + + err = item.Value(func(val []byte) error { + encodedBlock = val + return nil + }) + + block = Deserialize(encodedBlock) + + return err + }) + + if err != nil { + HandleError(err) + return nil, err + } + + iter.CurrentHash = block.PreviousHash + + return block, nil +} + +func initGenesis(coinbase []*Transaction) Block { + return Block{ + Index: 0, + UnixTimeStamp: time.Now().UTC().UnixNano(), + Hash: make([]byte, 32), + PreviousHash: nil, + Nonce: 0, + Difficulty: 0, + Transaction: coinbase, + } +} + +func (bc *Blockchain) FindTransaction(ID []byte) (Transaction, error) { + iter := bc.Iterator() + + for { + block, err := iter.Next() + HandleError(err) + + for _, tx := range block.Transaction { + if bytes.Compare(tx.ID, ID) == 0 { + return *tx, nil + } + + if len(block.PreviousHash) == 0 { + break + } + } + } +} + +func (bc *Blockchain) SignTransaction(tx *Transaction, privateKey ecdsa.PrivateKey) { + previousTxs := make(map[string]Transaction) + + for _, in := range tx.Inputs { + pTx, err := bc.FindTransaction(in.ID) + HandleError(err) + previousTxs[hex.EncodeToString(pTx.ID)] = pTx + } + + tx.Sign(privateKey, previousTxs) +} + +func (bc *Blockchain) VerifyTransaction(tx *Transaction) bool { + previousTxs := make(map[string]Transaction) + + for _, in := range tx.Inputs { + pTx, err := bc.FindTransaction(in.ID) + HandleError(err) + previousTxs[hex.EncodeToString(pTx.ID)] = pTx + } + + return tx.Verify(previousTxs) +} diff --git a/blockchain/output.go b/blockchain/output.go new file mode 100644 index 0000000..038c46f --- /dev/null +++ b/blockchain/output.go @@ -0,0 +1,7 @@ +package blockchain + +type Output struct { + Index int + Address string + Value int +} diff --git a/blockchain/transaction.go b/blockchain/transaction.go new file mode 100644 index 0000000..86d4ceb --- /dev/null +++ b/blockchain/transaction.go @@ -0,0 +1,243 @@ +package blockchain + +import ( + "bytes" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "encoding/gob" + "encoding/hex" + "fmt" + "math/big" + "runtime" + "strings" + + "github.com/MVRetailManager/MVInventoryChain/logging" + "github.com/MVRetailManager/MVInventoryChain/wallet" +) + +const ( + reward = 100 +) + +type Transaction struct { + ID []byte + Inputs []TxInput + Outputs []TxOutput +} + +func (tx *Transaction) SetID() { + var encoded bytes.Buffer + var hash [32]byte + + encode := gob.NewEncoder(&encoded) + err := encode.Encode(tx) + HandleError(err) + + hash = sha256.Sum256(encoded.Bytes()) + tx.ID = hash[:] +} + +func CoinbaseTx(to, data string) *Transaction { + if data == "" { + data = fmt.Sprintf("Reward to '%s'", to) + } + + twin := TxInput{[]byte{}, -1, nil, []byte(data)} + txout := NewTxOutput(reward, to) + + tx := Transaction{nil, []TxInput{twin}, []TxOutput{*txout}} + tx.SetID() + + return &tx +} + +func NewTransaction(from, to string, amount int, bc *Blockchain) *Transaction { + var inputs []TxInput + var outputs []TxOutput + + wallets, err := wallet.CreateWallets() + HandleError(err) + + w := wallets.GetWallet(from) + publicKeyHash := wallet.PublicKeyHash(w.PublicKey) + + acc, validOutputs := bc.FindSpendableOutputs(publicKeyHash, amount) + + if acc < amount { + fmt.Printf("Not enough funds on address %s\n", from) + logging.WarningLogger.Printf("Not enough funds on address %s\n", from) + runtime.Goexit() + } + + for txid, outs := range validOutputs { + txID, err := hex.DecodeString(txid) + HandleError(err) + + for _, out := range outs { + input := TxInput{txID, out, nil, w.PublicKey} + inputs = append(inputs, input) + } + } + + outputs = append(outputs, *NewTxOutput(amount, to)) + + if acc > amount { + outputs = append(outputs, *NewTxOutput(acc-amount, from)) + } + + tx := Transaction{nil, inputs, outputs} + tx.ID = tx.Hash() + + bc.SignTransaction(&tx, w.PrivateKey) + + return &tx +} + +func (tx *Transaction) IsCoinbase() bool { + return len(tx.Inputs) == 1 && len(tx.Inputs[0].ID) == 0 && tx.Inputs[0].OutputIndex == -1 +} + +func (tx Transaction) Serialize() []byte { + var encoded bytes.Buffer + + enc := gob.NewEncoder(&encoded) + err := enc.Encode(tx) + HandleError(err) + + return encoded.Bytes() +} + +func (tx *Transaction) Hash() []byte { + var hash [32]byte + + txCopy := *tx + txCopy.ID = []byte{} + + hash = sha256.Sum256(txCopy.Serialize()) + + return hash[:] +} + +func (tx *Transaction) Sign(privateKey ecdsa.PrivateKey, previousTxs map[string]Transaction) { + if tx.IsCoinbase() { + return + } + + for _, in := range tx.Inputs { + if previousTxs[hex.EncodeToString(in.ID)].ID == nil { + logging.ErrorLogger.Printf("Error with transaction %s, previous transaction does not exist.", hex.EncodeToString(in.ID)) + runtime.Goexit() + } + } + + txCopy := tx.TrimmedCopy() + + for inId, in := range txCopy.Inputs { + prevTx := previousTxs[hex.EncodeToString(in.ID)] + + txCopy.Inputs[inId].Signature = nil + txCopy.Inputs[inId].PublicKey = prevTx.Outputs[in.OutputIndex].PublicKeyHash + + txCopy.ID = txCopy.Hash() + + txCopy.Inputs[inId].PublicKey = nil + + r, s, err := ecdsa.Sign(rand.Reader, &privateKey, txCopy.ID) + HandleError(err) + + signature := append(r.Bytes(), s.Bytes()...) + tx.Inputs[inId].Signature = signature + } +} + +func (tx Transaction) TrimmedCopy() Transaction { + var inputs []TxInput + var outputs []TxOutput + + for _, in := range tx.Inputs { + inputs = append(inputs, TxInput{in.ID, in.OutputIndex, nil, nil}) + } + + for _, out := range tx.Outputs { + outputs = append(outputs, TxOutput{out.Value, out.PublicKeyHash}) + } + + txCopy := Transaction{tx.ID, inputs, outputs} + + return txCopy +} + +func (tx *Transaction) Verify(previousTxs map[string]Transaction) bool { + if tx.IsCoinbase() { + return true + } + + for _, in := range tx.Inputs { + if previousTxs[hex.EncodeToString(in.ID)].ID == nil { + logging.ErrorLogger.Printf("Error with transaction %s, previous transaction does not exist.", hex.EncodeToString(in.ID)) + runtime.Goexit() + } + } + + txCopy := tx.TrimmedCopy() + curve := elliptic.P256() + + for inId, in := range txCopy.Inputs { + prevTx := previousTxs[hex.EncodeToString(in.ID)] + + txCopy.Inputs[inId].Signature = nil + txCopy.Inputs[inId].PublicKey = prevTx.Outputs[in.OutputIndex].PublicKeyHash + + txCopy.ID = txCopy.Hash() + + txCopy.Inputs[inId].PublicKey = nil + + r := big.Int{} + s := big.Int{} + + sigLen := len(in.Signature) + + r.SetBytes(in.Signature[:(sigLen / 2)]) + s.SetBytes(in.Signature[(sigLen / 2):]) + + x := big.Int{} + y := big.Int{} + + keyLen := len(in.PublicKey) + + x.SetBytes(in.PublicKey[:(keyLen / 2)]) + y.SetBytes(in.PublicKey[(keyLen / 2):]) + + rawPublicKey := ecdsa.PublicKey{curve, &x, &y} + + if ecdsa.Verify(&rawPublicKey, txCopy.ID, &r, &s) == false { + return false + } + } + + return true +} + +func (tx Transaction) String() string { + var lines []string + + lines = append(lines, fmt.Sprintf("--- Transaction %x:", tx.ID)) + + for i, input := range tx.Inputs { + lines = append(lines, fmt.Sprintf(" Input %d", i)) + lines = append(lines, fmt.Sprintf(" TXID: %d", input.ID)) + lines = append(lines, fmt.Sprintf(" OutputIndex: %d", input.OutputIndex)) + lines = append(lines, fmt.Sprintf(" Signature: %x", input.Signature)) + lines = append(lines, fmt.Sprintf(" PublicKey: %x", input.PublicKey)) + } + + for i, output := range tx.Outputs { + lines = append(lines, fmt.Sprintf(" Output %d", i)) + lines = append(lines, fmt.Sprintf(" Value: %d", output.Value)) + lines = append(lines, fmt.Sprintf(" PublicKeyHash: %x", output.PublicKeyHash)) + } + + return strings.Join(lines, "\n") +} diff --git a/blockchain/tx.go b/blockchain/tx.go new file mode 100644 index 0000000..72a1921 --- /dev/null +++ b/blockchain/tx.go @@ -0,0 +1,48 @@ +package blockchain + +import ( + "bytes" + "runtime" + + logging "github.com/MVRetailManager/MVInventoryChain/logging" + "github.com/MVRetailManager/MVInventoryChain/wallet" +) + +type TxOutput struct { + Value int + PublicKeyHash []byte +} + +type TxInput struct { + ID []byte + OutputIndex int + Signature []byte + PublicKey []byte +} + +func (in *TxInput) UsesKey(publicKeyHash []byte) bool { + lockingHash := wallet.PublicKeyHash(in.PublicKey) + + return bytes.Compare(lockingHash, publicKeyHash) == 0 +} + +func (out *TxOutput) Lock(address []byte) { + finalKey, err := wallet.Base58Decode(address) + if err != nil { + logging.ErrorLogger.Printf("%v", err) + runtime.Goexit() + } + + out.PublicKeyHash = finalKey[1 : len(finalKey)-4] +} + +func (out *TxOutput) IsLockedWithkey(publicKeyHash []byte) bool { + return bytes.Compare(out.PublicKeyHash, publicKeyHash) == 0 +} + +func NewTxOutput(value int, address string) *TxOutput { + txOutput := &TxOutput{value, nil} + txOutput.Lock([]byte(address)) + + return txOutput +} diff --git a/blockchain/utils.go b/blockchain/utils.go new file mode 100644 index 0000000..21d6bf9 --- /dev/null +++ b/blockchain/utils.go @@ -0,0 +1,9 @@ +package blockchain + +import logging "github.com/MVRetailManager/MVInventoryChain/logging" + +func HandleError(err error) { + if err != nil { + logging.ErrorLogger.Printf(err.Error()) + } +} diff --git a/cli/cli.go b/cli/cli.go new file mode 100644 index 0000000..7e6d4bd --- /dev/null +++ b/cli/cli.go @@ -0,0 +1,232 @@ +package cli + +import ( + "flag" + "fmt" + "os" + "runtime" + "time" + + blockchainPKG "github.com/MVRetailManager/MVInventoryChain/blockchain" + "github.com/MVRetailManager/MVInventoryChain/logging" + "github.com/MVRetailManager/MVInventoryChain/wallet" +) + +type CLI struct{} + +var bc blockchainPKG.Blockchain + +func (cli *CLI) printUsage() { + logging.InfoLogger.Println("Usage command executed.") + + fmt.Println("Usage:") + fmt.Println(" getbalance -address ADDRESS - Get balance of ADDRESS") + fmt.Println(" createblockchain -address ADDRESS - Create a new blockchain and save it to disk, ADDRESS will be the address of the coinbase transaction") + fmt.Println(" printchain - Print the blockchain") + fmt.Println(" send -from FROM -to TO- amount AMOUNT - Send AMOUNT of coins from FROM to TO") + fmt.Println(" createwallet - Create a new wallet") + fmt.Println(" listaddresses - List all addresses stored within wallet file") +} + +func (cli *CLI) validateArgs() { + if len(os.Args) < 2 { + cli.printUsage() + runtime.Goexit() + } +} + +func (cli *CLI) printChain() { + bc.ContinueBlockchain("") + defer bc.Database.Close() + + iter := bc.Iterator() + + for { + block, err := iter.Next() + blockchainPKG.HandleError(err) + + fmt.Printf("\nS==========%d==========S\n", block.Index) + fmt.Printf("Previous Hash: %x\n", block.PreviousHash) + fmt.Printf("Hash: %x\n", block.Hash) + fmt.Printf("Nonce: %d\n", block.Nonce) + fmt.Printf("Difficulty: %d\n", block.Difficulty) + fmt.Printf("TimeStamp: %d\n", block.UnixTimeStamp) + fmt.Printf("Transactions:\n") + + for _, tx := range block.Transaction { + fmt.Println(tx) + } + + fmt.Printf("E==========%d==========E\n", block.Index) + } +} + +func (cli *CLI) createBlockchain(address string) { + if !wallet.ValidateAddress(address) { + fmt.Printf("%s is not a valid address\n", address) + logging.ErrorLogger.Printf("%s is not a valid address", address) + runtime.Goexit() + } + + bc.InitBlockchain(address) + bc.Database.Close() + fmt.Println("Success!") +} + +func (cli *CLI) getBalance(address string) { + if !wallet.ValidateAddress(address) { + fmt.Printf("%s is not a valid address\n", address) + logging.ErrorLogger.Printf("%s is not a valid address", address) + runtime.Goexit() + } + + bc.ContinueBlockchain(address) + defer bc.Database.Close() + + balance := 0 + + finalHash := wallet.Base58Encode([]byte(address)) + publicKeyHash := finalHash[1 : len(finalHash)-4] + + UTXOs := bc.HandleUnspentTxs(publicKeyHash) + + for _, out := range UTXOs { + balance += out.Value + } + + fmt.Printf("Balance of '%s': %d\n", address, balance) +} + +func (cli *CLI) send(from, to string, amount int) { + if !wallet.ValidateAddress(to) { + fmt.Printf("%s is not a valid address\n", to) + logging.ErrorLogger.Printf("%s is not a valid address", to) + runtime.Goexit() + } + if !wallet.ValidateAddress(from) { + fmt.Printf("%s is not a valid address\n", from) + logging.ErrorLogger.Printf("%s is not a valid address", from) + runtime.Goexit() + } + + bc.ContinueBlockchain(from) + defer bc.Database.Close() + + tx := blockchainPKG.NewTransaction(from, to, amount, &bc) + + nbIndex, _ := bc.Database.Size() + bc.AddBlock(*blockchainPKG.NewBlock(int(nbIndex), time.Now().UTC().UnixNano(), bc.LastHash, []*blockchainPKG.Transaction{tx})) + + fmt.Print("Success!") +} + +func (cli *CLI) createWallet() { + wallets, _ := wallet.CreateWallets() + address := wallets.AddWallet() + wallets.SaveFile() + + fmt.Printf("New address: %s\n", address) +} + +func (cli *CLI) listAddresses() { + wallets, _ := wallet.CreateWallets() + addresses := wallets.GetAllAddresses() + + for _, address := range addresses { + fmt.Println(address) + } +} + +func (cli *CLI) Run() { + bc = blockchainPKG.Blockchain{} + + cli.validateArgs() + + getBalanceCmd := flag.NewFlagSet("getbalance", flag.ExitOnError) + createBlockchainCmd := flag.NewFlagSet("createblockchain", flag.ExitOnError) + printChainCmd := flag.NewFlagSet("printchain", flag.ExitOnError) + sendCmd := flag.NewFlagSet("send", flag.ExitOnError) + createWalletsCmd := flag.NewFlagSet("createwallet", flag.ExitOnError) + listAddressesCmd := flag.NewFlagSet("listaddresses", flag.ExitOnError) + + getBalanceAddress := getBalanceCmd.String("address", "", "The address to get balance for") + createBlockchainAddress := createBlockchainCmd.String("address", "", "The address to send genesis block reward to") + 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:]) + if err != nil { + logging.ErrorLogger.Panic(err) + } + case "createblockchain": + err := createBlockchainCmd.Parse(os.Args[2:]) + if err != nil { + logging.ErrorLogger.Panic(err) + } + case "printchain": + err := printChainCmd.Parse(os.Args[2:]) + if err != nil { + logging.ErrorLogger.Panic(err) + } + case "send": + err := sendCmd.Parse(os.Args[2:]) + if err != nil { + logging.ErrorLogger.Panic(err) + } + case "createwallet": + err := createWalletsCmd.Parse(os.Args[2:]) + if err != nil { + logging.ErrorLogger.Panic(err) + } + case "listaddresses": + err := listAddressesCmd.Parse(os.Args[2:]) + if err != nil { + logging.ErrorLogger.Panic(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) + } + + if createWalletsCmd.Parsed() { + cli.createWallet() + } + + if listAddressesCmd.Parsed() { + cli.listAddresses() + } + + runtime.Goexit() +} diff --git a/customErrors/customErrors.go b/customErrors/customErrors.go new file mode 100644 index 0000000..f74448e --- /dev/null +++ b/customErrors/customErrors.go @@ -0,0 +1,162 @@ +package customErrors + +/* +import ( + "errors" + "fmt" +) + +// MismatchedIndex is an error type that is returned when the index of a block +// does not match the index of the previous block. +type MismatchedIndex struct { + ExpectedIndex int + ActualIndex int + statusCode int + err error +} + +func (mi *MismatchedIndex) Error() string { + return fmt.Sprintf("MismatchedIndexError: Expected: %d, Got: %d", mi.ExpectedIndex, mi.ActualIndex) +} + +func (mi MismatchedIndex) DoError() error { + return &MismatchedIndex{ + ExpectedIndex: mi.ExpectedIndex, + ActualIndex: mi.ActualIndex, + statusCode: 503, + err: errors.New("MismatchedIndexError"), + } +} + +// AchronologicalTimestamp is an error type that is returned when the timestamp +// of a block is earlier than the timestamp of the previous block. +type AchronologicalTimestamp struct { + ExpectedTimestamp int64 + ActualTimestamp int64 + statusCode int + err error +} + +func (ai *AchronologicalTimestamp) Error() string { + return fmt.Sprintf("AchronologicalTimestampError: Expected: Timestamp > %d, Got: %d", ai.ExpectedTimestamp, ai.ActualTimestamp) +} + +func (ai AchronologicalTimestamp) DoError() error { + return &AchronologicalTimestamp{ + ExpectedTimestamp: ai.ExpectedTimestamp, + ActualTimestamp: ai.ActualTimestamp, + statusCode: 503, + err: errors.New("AchronologicalTimestampError"), + } +} + +// InvalidTimestamp is an error type that is returned when the timestamp of a +// block has not happened yet. +type InvalidTimestamp struct { + ExpectedTimestamp int64 + ActualTimestamp int64 + statusCode int + err error +} + +func (it *InvalidTimestamp) Error() string { + return fmt.Sprintf("InvalidTimestampError: Expected: Timestamp < %d, Got: %d", it.ExpectedTimestamp, it.ActualTimestamp) +} + +func (it InvalidTimestamp) DoError() error { + return &InvalidTimestamp{ + ExpectedTimestamp: it.ExpectedTimestamp, + ActualTimestamp: it.ActualTimestamp, + statusCode: 503, + err: errors.New("InvalidTimestampError"), + } +} + +// InvalidPreviousHash is an error type that is returned when the previous hash +// of a block does not match the hash of the previous block. +type InvalidPreviousHash struct { + ExpectedHash []byte + ActualHash []byte + statusCode int + err error +} + +func (ip *InvalidPreviousHash) Error() string { + return fmt.Sprintf("InvalidPreviousHashError: Expected: %x, Got: %x", ip.ExpectedHash, ip.ActualHash) +} + +func (ip InvalidPreviousHash) DoError() error { + return &InvalidPreviousHash{ + ExpectedHash: ip.ExpectedHash, + ActualHash: ip.ActualHash, + statusCode: 503, + err: errors.New("InvalidPreviousHashError"), + } +} + +// InvalidGenesisBlock is an error type that is returned when the genesis block +// is invalid. +type InvalidGenesisBlock struct { + ExpectedFormat []byte + ActualFormat []byte + statusCode int + err error +} + +func (ig *InvalidGenesisBlock) Error() string { + return fmt.Sprintf("InvalidGenesisBlockError: Expected format: %x, Got: %x", ig.ExpectedFormat, ig.ActualFormat) +} + +func (ig InvalidGenesisBlock) DoError() error { + return &InvalidGenesisBlock{ + ExpectedFormat: ig.ExpectedFormat, + ActualFormat: ig.ActualFormat, + statusCode: 503, + err: errors.New("InvalidGenesisBlockError"), + } +} + +// InsufficientInputValue is an error type that is returned when the input value +// of a transaction is less than the minimum value. +type InsufficientInputValue struct { + ExpectedValue int + ActualValue int + statusCode int + err error +} + +func (ii *InsufficientInputValue) Error() string { + return fmt.Sprintf("InsufficientInputValueError: Expected: <= %d, Got: %d", ii.ExpectedValue, ii.ActualValue) +} + +func (ii InsufficientInputValue) DoError() error { + return &InsufficientInputValue{ + ExpectedValue: ii.ExpectedValue, + ActualValue: ii.ActualValue, + statusCode: 503, + err: errors.New("InsufficientInputValueError"), + } +} + +// InvalidInput is an error type that is returned when the input of a transaction +// is < 0. +type InvalidInput struct { + ExpectedValue int + ActualValue int + statusCode int + err error +} + +func (ii *InvalidInput) Error() string { + return fmt.Sprintf("InvalidInputError: Expected: > %d, Got: %d", ii.ExpectedValue, ii.ActualValue) +} + +func (ii InvalidInput) DoError() error { + return &InvalidInput{ + ExpectedValue: ii.ExpectedValue, + ActualValue: ii.ActualValue, + statusCode: 503, + err: errors.New("InvalidInputError"), + } +} +*/ diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..f7fa060 --- /dev/null +++ b/go.mod @@ -0,0 +1,27 @@ +module github.com/MVRetailManager/MVInventoryChain + +go 1.18 + +require github.com/dgraph-io/badger v1.6.2 + +require ( + github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96 // indirect + github.com/cespare/xxhash v1.1.0 // indirect + github.com/cespare/xxhash/v2 v2.1.1 // indirect + github.com/dgraph-io/badger/v3 v3.2103.2 // indirect + github.com/dgraph-io/ristretto v0.1.0 // indirect + github.com/dustin/go-humanize v1.0.0 // indirect + github.com/gogo/protobuf v1.3.2 // indirect + github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b // indirect + github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6 // indirect + github.com/golang/protobuf v1.3.1 // indirect + github.com/golang/snappy v0.0.3 // indirect + github.com/google/flatbuffers v1.12.1 // indirect + github.com/klauspost/compress v1.12.3 // indirect + github.com/mr-tron/base58 v1.2.0 + github.com/pkg/errors v0.9.1 // indirect + go.opencensus.io v0.22.5 // indirect + golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d + golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 // indirect + golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..a171d3a --- /dev/null +++ b/go.sum @@ -0,0 +1,146 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96 h1:cTp8I5+VIoKjsnZuH8vjyaysT/ses3EvZeaV/1UkF2M= +github.com/AndreasBriese/bbloom v0.0.0-20190825152654-46b345b51c96/go.mod h1:bOvUY6CB00SOBii9/FifXqc0awNKxLFCL/+pkDPuyl8= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8= +github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko= +github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= +github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-etcd v2.0.0+incompatible/go.mod h1:Jez6KQU2B/sWsbdaef3ED8NzMklzPG4d5KIOhIy30Tk= +github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgraph-io/badger v1.6.2 h1:mNw0qs90GVgGGWylh0umH5iag1j6n/PeJtNvL6KY/x8= +github.com/dgraph-io/badger v1.6.2/go.mod h1:JW2yswe3V058sS0kZ2h/AXeDSqFjxnZcRrVH//y2UQE= +github.com/dgraph-io/badger/v3 v3.2103.2 h1:dpyM5eCJAtQCBcMCZcT4UBZchuTJgCywerHHgmxfxM8= +github.com/dgraph-io/badger/v3 v3.2103.2/go.mod h1:RHo4/GmYcKKh5Lxu63wLEMHJ70Pac2JqZRYGhlyAo2M= +github.com/dgraph-io/ristretto v0.0.2/go.mod h1:KPxhHT9ZxKefz+PCeOGsrHpl1qZ7i70dGTu2u+Ahh6E= +github.com/dgraph-io/ristretto v0.1.0 h1:Jv3CGQHp9OjuMBSne1485aDpUkTKEcUqF+jm/LuerPI= +github.com/dgraph-io/ristretto v0.1.0/go.mod h1:fux0lOrBhrVCJd3lcTHsIJhq1T2rokOu6v9Vcb3Q9ug= +github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2/go.mod h1:SqUrOPUnsFjfmXRMNPybcSiG0BgUW2AuFH8PAnS2iTw= +github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo= +github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6 h1:ZgQEtGgCBiWRM39fZuwSd1LwSqqSW0hOdXCYYDX0R3I= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/snappy v0.0.3 h1:fHPg5GQYlCeLIPB9BZqMVR5nR9A+IM5zcgeTdjMYmLA= +github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/flatbuffers v1.12.1 h1:MVlul7pQNoDzWRLTw5imwYsl+usrS1TXG2H4jg6ImGw= +github.com/google/flatbuffers v1.12.1/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/compress v1.12.3 h1:G5AfA94pHPysR56qqrkO2pxEexdDzrpFJ6yt/VqWxVU= +github.com/klauspost/compress v1.12.3/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.0/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +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/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g= +github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/spaolacci/murmur3 v1.1.0/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= +github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= +github.com/spf13/cobra v0.0.5/go.mod h1:3K3wKZymM7VvHMDS9+Akkh4K60UwM26emMESw8tLCHU= +github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo= +github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/spf13/viper v1.3.2/go.mod h1:ZiWeW+zYFKm7srdB9IoDzzZXaJaI5eL9QjNiN/DMA2s= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= +github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +go.opencensus.io v0.22.5 h1:dntmOdLpSpHlVqbW5Eay97DelsZHe+55D+xC6i0dDS0= +go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= +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/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d h1:sK3txAijHtOK88l68nt020reeT1ZdKLIYetKl95FzVY= +golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974 h1:IX6qOQeG5uLjB/hjjwjedwfjND0hgjPMMyO1RoIXQNI= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2 h1:CIJ76btIcR3eFI5EgSo6k1qKw9KJexJuRLI9G7Hp5wE= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +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-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c h1:VwygUrnw9jn88c4u8GD3rZQbqrP/tgas88tPUbBxQrk= +golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 h1:SrN+KX8Art/Sf4HNj6Zcz06G7VEz+7w9tdXTPOZ7+l4= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +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= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/logging/logging.go b/logging/logging.go new file mode 100644 index 0000000..50bf05f --- /dev/null +++ b/logging/logging.go @@ -0,0 +1,29 @@ +package logging + +import ( + "io" + "log" + "os" +) + +var ( + InfoLogger *log.Logger + ErrorLogger *log.Logger + WarningLogger *log.Logger + BlocksLogger *log.Logger +) + +func SetupLogger() { + file, err := os.OpenFile("logs.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666) + + if err != nil { + ErrorLogger.Fatal(err) + } + + multiWriter := io.MultiWriter(os.Stdout, file) + + InfoLogger = log.New(multiWriter, "INFO: ", log.LstdFlags|log.Lshortfile|log.LUTC|log.Lmicroseconds) + WarningLogger = log.New(multiWriter, "WARNING: ", log.LstdFlags|log.Lshortfile|log.LUTC|log.Lmicroseconds) + ErrorLogger = log.New(multiWriter, "ERROR: ", log.LstdFlags|log.Lshortfile|log.LUTC|log.Lmicroseconds) + BlocksLogger = log.New(multiWriter, "BLOCKS: ", log.LstdFlags|log.Lshortfile|log.LUTC|log.Lmicroseconds) +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..4033968 --- /dev/null +++ b/main.go @@ -0,0 +1,20 @@ +package main + +import ( + "os" + + "github.com/MVRetailManager/MVInventoryChain/cli" + "github.com/MVRetailManager/MVInventoryChain/logging" +) + +func init() { + logging.SetupLogger() + + logging.InfoLogger.Println("Starting MVInventoryChain...") +} + +func main() { + defer os.Exit(0) + cmdline := cli.CLI{} + cmdline.Run() +} diff --git a/test/block_errors_test.go b/test/block_errors_test.go new file mode 100644 index 0000000..bf80ec7 --- /dev/null +++ b/test/block_errors_test.go @@ -0,0 +1,600 @@ +package test + +/* +import ( + "testing" + "time" + + blockchainPKG "github.com/MVRetailManager/MVInventoryChain/blockchain" +) + +// func BenchmarkTest(b *testing.B) { +// for i := 0; i < b.N; i++ { +// test() +// } +// } + +// func ExampleMain() { +// main() +// // Output: Hello, world. +// } + +// MismatchedIndex Tests +func TestNewBlockMismatchedIndexLess(t *testing.T) { + genesisBlock := blockchainPKG.Block{ + Index: 0, + UnixTimeStamp: time.Now().UTC().UnixNano(), + Hash: make([]byte, 32), + PreviousHash: nil, + Nonce: 0, + Difficulty: 0, + Transaction: nil, + } + + bc := blockchainPKG.Blockchain{} + bc.NewBlockchain(genesisBlock) + + block := blockchainPKG.NewBlock( + -1, + time.Now().UTC().UnixNano(), + genesisBlock.Hash, + 1, + []blockchainPKG.Transaction{}, + ) + + block.Mine() + + if bc.AddBlock(*block) == nil { + t.Errorf("Expected false, got true") + } +} + +func TestNewBlockMismatchedIndexGreater(t *testing.T) { + genesisBlock := blockchainPKG.Block{ + Index: 0, + UnixTimeStamp: time.Now().UTC().UnixNano(), + Hash: make([]byte, 32), + PreviousHash: nil, + Nonce: 0, + Difficulty: 0, + Transaction: nil, + } + + bc := blockchainPKG.Blockchain{} + bc.NewBlockchain(genesisBlock) + + block := blockchainPKG.NewBlock( + 2, + time.Now().UTC().UnixNano(), + genesisBlock.Hash, + 1, + []blockchainPKG.Transaction{}, + ) + + block.Mine() + + if bc.AddBlock(*block) == nil { + t.Errorf("Expected false, got true") + } +} + +func TestNewBlockMismatchedIndexEqual(t *testing.T) { + genesisBlock := blockchainPKG.Block{ + Index: 0, + UnixTimeStamp: time.Now().UTC().UnixNano(), + Hash: make([]byte, 32), + PreviousHash: nil, + Nonce: 0, + Difficulty: 0, + Transaction: nil, + } + + bc := blockchainPKG.Blockchain{} + bc.NewBlockchain(genesisBlock) + + block := blockchainPKG.NewBlock( + 0, + time.Now().UTC().UnixNano(), + genesisBlock.Hash, + 1, + []blockchainPKG.Transaction{}, + ) + + block.Mine() + + if bc.AddBlock(*block) == nil { + t.Errorf("Expected false, got true") + } +} + +func TestNewBlockMismatchedIndex(t *testing.T) { + genesisBlock := blockchainPKG.Block{ + Index: 0, + UnixTimeStamp: time.Now().UTC().UnixNano(), + Hash: make([]byte, 32), + PreviousHash: nil, + Nonce: 0, + Difficulty: 0, + Transaction: nil, + } + + bc := blockchainPKG.Blockchain{} + bc.NewBlockchain(genesisBlock) + + block := blockchainPKG.NewBlock( + 1, + time.Now().UTC().UnixNano(), + genesisBlock.Hash, + 1, + []blockchainPKG.Transaction{}, + ) + + block.Mine() + + if bc.AddBlock(*block) != nil { + t.Errorf("Expected false, got true") + } +} + +// AchronologicalTimeStamp Test +func TestNewBlockAchronologicalTimeStamp(t *testing.T) { + genesisBlock := blockchainPKG.Block{ + Index: 0, + UnixTimeStamp: time.Now().UTC().UnixNano(), + Hash: make([]byte, 32), + PreviousHash: nil, + Nonce: 0, + Difficulty: 0, + Transaction: nil, + } + + bc := blockchainPKG.Blockchain{} + bc.NewBlockchain(genesisBlock) + + block := blockchainPKG.NewBlock( + 1, + 10, + genesisBlock.Hash, + 1, + []blockchainPKG.Transaction{}, + ) + + block.Mine() + + if bc.AddBlock(*block) == nil { + t.Errorf("Expected false, got true") + } +} + +func TestNewBlockChronologicalTimeStamp(t *testing.T) { + genesisBlock := blockchainPKG.Block{ + Index: 0, + UnixTimeStamp: time.Now().UTC().UnixNano(), + Hash: make([]byte, 32), + PreviousHash: nil, + Nonce: 0, + Difficulty: 0, + Transaction: nil, + } + + bc := blockchainPKG.Blockchain{} + bc.NewBlockchain(genesisBlock) + + block := blockchainPKG.NewBlock( + 1, + time.Now().UTC().UnixNano(), + genesisBlock.Hash, + 1, + []blockchainPKG.Transaction{}, + ) + + block.Mine() + + if bc.AddBlock(*block) != nil { + t.Errorf("Expected false, got true") + } +} + +// InvalidTimestamp Test +func TestNewBlockInvalidTimestamp(t *testing.T) { + genesisBlock := blockchainPKG.Block{ + Index: 0, + UnixTimeStamp: time.Now().UTC().UnixNano(), + Hash: make([]byte, 32), + PreviousHash: nil, + Nonce: 0, + Difficulty: 0, + Transaction: nil, + } + + bc := blockchainPKG.Blockchain{} + bc.NewBlockchain(genesisBlock) + + block := blockchainPKG.NewBlock( + 1, + time.Now().UTC().UnixNano()+1000000000000000000, + genesisBlock.Hash, + 1, + []blockchainPKG.Transaction{}, + ) + + block.Mine() + + if bc.AddBlock(*block) == nil { + t.Errorf("Expected false, got true") + } +} + +func TestNewBlockValidTimestamp(t *testing.T) { + genesisBlock := blockchainPKG.Block{ + Index: 0, + UnixTimeStamp: time.Now().UTC().UnixNano(), + Hash: make([]byte, 32), + PreviousHash: nil, + Nonce: 0, + Difficulty: 0, + Transaction: nil, + } + + bc := blockchainPKG.Blockchain{} + bc.NewBlockchain(genesisBlock) + + block := blockchainPKG.NewBlock( + 1, + time.Now().UTC().UnixNano(), + genesisBlock.Hash, + 1, + []blockchainPKG.Transaction{}, + ) + + block.Mine() + + if bc.AddBlock(*block) != nil { + t.Errorf("Expected false, got true") + } +} + +// InvalidPreviousHash Test +func TestNewBlockInvalidPreviousHashGenesis(t *testing.T) { + genesisBlock := blockchainPKG.Block{ + Index: 0, + UnixTimeStamp: time.Now().UTC().UnixNano(), + Hash: make([]byte, 32), + PreviousHash: nil, + Nonce: 0, + Difficulty: 0, + Transaction: nil, + } + + bc := blockchainPKG.Blockchain{} + bc.NewBlockchain(genesisBlock) + + block := blockchainPKG.NewBlock( + 1, + time.Now().UTC().UnixNano(), + []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, + 1, + []blockchainPKG.Transaction{}, + ) + + block.Mine() + + if bc.AddBlock(*block) == nil { + t.Errorf("Expected false, got true") + } +} + +func TestNewBlockInvalidPreviousHash(t *testing.T) { + genesisBlock := blockchainPKG.Block{ + Index: 0, + UnixTimeStamp: time.Now().UTC().UnixNano(), + Hash: make([]byte, 32), + PreviousHash: nil, + Nonce: 0, + Difficulty: 0, + Transaction: nil, + } + + bc := blockchainPKG.Blockchain{} + bc.NewBlockchain(genesisBlock) + + block := blockchainPKG.NewBlock( + 1, + time.Now().UTC().UnixNano(), + genesisBlock.Hash, + 1, + []blockchainPKG.Transaction{}, + ) + + block.Mine() + + if bc.AddBlock(*block) != nil { + t.Errorf("Unexpected error") + } + + block2 := blockchainPKG.NewBlock( + 2, + time.Now().UTC().UnixNano(), + []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}, + 1, + []blockchainPKG.Transaction{}, + ) + + block2.Mine() + + if bc.AddBlock(*block2) == nil { + t.Errorf("Expected false, got true") + } +} + +func TestValidPreviousHashGenesis(t *testing.T) { + genesisBlock := blockchainPKG.Block{ + Index: 0, + UnixTimeStamp: time.Now().UTC().UnixNano(), + Hash: make([]byte, 32), + PreviousHash: nil, + Nonce: 0, + Difficulty: 0, + Transaction: nil, + } + + bc := blockchainPKG.Blockchain{} + bc.NewBlockchain(genesisBlock) + + block := blockchainPKG.NewBlock( + 1, + time.Now().UTC().UnixNano(), + genesisBlock.Hash, + 1, + []blockchainPKG.Transaction{}, + ) + + block.Mine() + + if bc.AddBlock(*block) != nil { + t.Errorf("Expected false, got true") + } +} + +func TestValidPreviousHash(t *testing.T) { + genesisBlock := blockchainPKG.Block{ + Index: 0, + UnixTimeStamp: time.Now().UTC().UnixNano(), + Hash: make([]byte, 32), + PreviousHash: nil, + Nonce: 0, + Difficulty: 0, + Transaction: nil, + } + + bc := blockchainPKG.Blockchain{} + bc.NewBlockchain(genesisBlock) + + block := blockchainPKG.NewBlock( + 1, + time.Now().UTC().UnixNano(), + genesisBlock.Hash, + 1, + []blockchainPKG.Transaction{}, + ) + + block.Mine() + + if bc.AddBlock(*block) != nil { + t.Errorf("Unexpected error") + } + + block2 := blockchainPKG.NewBlock( + 2, + time.Now().UTC().UnixNano(), + block.Hash, + 1, + []blockchainPKG.Transaction{}, + ) + + block2.Mine() + + if bc.AddBlock(*block2) != nil { + t.Errorf("Expected false, got true") + } +} + +// InvalidGenesisBlock Test +func TestNewBlockInvalidGenesisBlock(t *testing.T) { + genesisBlock := blockchainPKG.Block{ + Index: 0, + UnixTimeStamp: time.Now().UTC().UnixNano(), + Hash: []byte{1, 2, 3, 4, 5, 6}, + PreviousHash: nil, + Nonce: 0, + Difficulty: 0, + Transaction: nil, + } + + bc := blockchainPKG.Blockchain{} + bc.NewBlockchain(genesisBlock) + + block := blockchainPKG.NewBlock( + 1, + time.Now().UTC().UnixNano(), + genesisBlock.Hash, + 1, + []blockchainPKG.Transaction{}, + ) + + block.Mine() + + if bc.AddBlock(*block) == nil { + t.Errorf("Expected false, got true") + } +} + +func TestNewBlockValidGenesisBlock(t *testing.T) { + genesisBlock := blockchainPKG.Block{ + Index: 0, + UnixTimeStamp: time.Now().UTC().UnixNano(), + Hash: make([]byte, 32), + PreviousHash: nil, + Nonce: 0, + Difficulty: 0, + Transaction: nil, + } + + bc := blockchainPKG.Blockchain{} + bc.NewBlockchain(genesisBlock) + + block := blockchainPKG.NewBlock( + 1, + time.Now().UTC().UnixNano(), + genesisBlock.Hash, + 1, + []blockchainPKG.Transaction{}, + ) + + block.Mine() + + if bc.AddBlock(*block) != nil { + t.Errorf("Expected false, got true") + } +} + +// InsufficientInputValue Test +func TestNewBlockInsufficientInputValue(t *testing.T) { + genesisBlock := blockchainPKG.Block{ + Index: 0, + UnixTimeStamp: time.Now().UTC().UnixNano(), + Hash: make([]byte, 32), + PreviousHash: nil, + Nonce: 0, + Difficulty: 0, + Transaction: nil, + } + + bc := blockchainPKG.Blockchain{} + bc.NewBlockchain(genesisBlock) + + block := blockchainPKG.NewBlock( + 1, + time.Now().UTC().UnixNano(), + genesisBlock.Hash, + 1, + []blockchainPKG.Transaction{ + { + Inputs: []blockchainPKG.Output{ + { + Index: 0, + Address: "Bob", + Value: 1, + }, + }, + Outputs: []blockchainPKG.Output{ + { + Index: 0, + Address: "Alice", + Value: 2, + }, + }, + }, + }, + ) + + block.Mine() + + if bc.AddBlock(*block) == nil { + t.Errorf("Expected false, got true") + } +} + +func TestNewBlockSufficientInputValue(t *testing.T) { + genesisBlock := blockchainPKG.Block{ + Index: 0, + UnixTimeStamp: time.Now().UTC().UnixNano(), + Hash: make([]byte, 32), + PreviousHash: nil, + Nonce: 0, + Difficulty: 0, + Transaction: nil, + } + + bc := blockchainPKG.Blockchain{} + bc.NewBlockchain(genesisBlock) + + block := blockchainPKG.NewBlock( + 1, + time.Now().UTC().UnixNano(), + genesisBlock.Hash, + 1, + []blockchainPKG.Transaction{ + { + Inputs: []blockchainPKG.Output{ + { + Index: 0, + Address: "Bob", + Value: 1, + }, + }, + Outputs: []blockchainPKG.Output{ + { + Index: 0, + Address: "Alice", + Value: 1, + }, + }, + }, + }, + ) + + block.Mine() + + if bc.AddBlock(*block) != nil { + t.Errorf("Expected false, got true") + } +} + +// InvalidInput Test +func TestNewBlockInvalidInput(t *testing.T) { + genesisBlock := blockchainPKG.Block{ + Index: 0, + UnixTimeStamp: time.Now().UTC().UnixNano(), + Hash: make([]byte, 32), + PreviousHash: nil, + Nonce: 0, + Difficulty: 0, + Transaction: nil, + } + + bc := blockchainPKG.Blockchain{} + bc.NewBlockchain(genesisBlock) + + block := blockchainPKG.NewBlock( + 1, + time.Now().UTC().UnixNano(), + genesisBlock.Hash, + 1, + []blockchainPKG.Transaction{ + { + Inputs: []blockchainPKG.Output{ + { + Index: 0, + Address: "Bob", + Value: -1, + }, + }, + Outputs: []blockchainPKG.Output{ + { + Index: 0, + Address: "Alice", + Value: -1, + }, + }, + }, + }, + ) + + block.Mine() + + if bc.AddBlock(*block) == nil { + t.Errorf("Expected false, got true") + } +} +*/ diff --git a/wallet/utils.go b/wallet/utils.go new file mode 100644 index 0000000..3bc8a1e --- /dev/null +++ b/wallet/utils.go @@ -0,0 +1,13 @@ +package wallet + +import ( + "github.com/mr-tron/base58" +) + +func Base58Encode(input []byte) []byte { + return []byte(base58.Encode(input)) +} + +func Base58Decode(input []byte) ([]byte, error) { + return base58.Decode(string(input[:])) +} diff --git a/wallet/wallet.go b/wallet/wallet.go new file mode 100644 index 0000000..9adc6e4 --- /dev/null +++ b/wallet/wallet.go @@ -0,0 +1,94 @@ +package wallet + +import ( + "bytes" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/sha256" + "runtime" + + "golang.org/x/crypto/ripemd160" + + "github.com/MVRetailManager/MVInventoryChain/logging" +) + +const ( + checksumLen = 4 + version = byte(0x00) +) + +type Wallet struct { + PrivateKey ecdsa.PrivateKey + PublicKey []byte +} + +func NewKeyPair() (ecdsa.PrivateKey, []byte) { + curve := elliptic.P256() + + priKey, err := ecdsa.GenerateKey(curve, rand.Reader) + + if err != nil { + logging.ErrorLogger.Printf("%v", err) + runtime.Goexit() + } + + pubKey := append(priKey.PublicKey.X.Bytes(), priKey.PublicKey.Y.Bytes()...) + + return *priKey, pubKey +} + +func NewWallet() *Wallet { + privateKey, publicKey := NewKeyPair() + + return &Wallet{privateKey, publicKey} +} + +func PublicKeyHash(pubKey []byte) []byte { + pubHash := sha256.Sum256(pubKey) + + hasher := ripemd160.New() + _, err := hasher.Write(pubHash[:]) + if err != nil { + logging.ErrorLogger.Printf("%v", err) + runtime.Goexit() + } + + publicRipMD160Hash := hasher.Sum(nil) + + return publicRipMD160Hash +} + +func Checksum(data []byte) []byte { + fstHash := sha256.Sum256(data) + sndHash := sha256.Sum256(fstHash[:]) + + return sndHash[:checksumLen] +} + +func (w Wallet) Address() []byte { + pubHash := PublicKeyHash(w.PublicKey) + + versionHash := append([]byte{version}, pubHash...) + checksum := Checksum(versionHash) + + fullHash := append(versionHash, checksum...) + + address := Base58Encode(fullHash) + + return address +} + +func ValidateAddress(address string) bool { + fullHash, err := Base58Decode([]byte(address)) + if err != nil { + return false + } + + actualChecksum := fullHash[len(fullHash)-checksumLen:] + version := fullHash[0] + pubKeyHash := fullHash[1 : len(fullHash)-checksumLen] + targetChecksum := Checksum(append([]byte{version}, pubKeyHash...)) + + return bytes.Compare(actualChecksum, targetChecksum) == 0 +} diff --git a/wallet/wallets.go b/wallet/wallets.go new file mode 100644 index 0000000..e0ebeaa --- /dev/null +++ b/wallet/wallets.go @@ -0,0 +1,98 @@ +package wallet + +import ( + "bytes" + "crypto/elliptic" + "encoding/gob" + "fmt" + "io/ioutil" + "os" + "runtime" + + "github.com/MVRetailManager/MVInventoryChain/logging" +) + +const walletFile = "./tmp/wallets.dat" + +type Wallets struct { + Wallets map[string]*Wallet +} + +func (ws *Wallets) SaveFile() { + var content bytes.Buffer + + gob.Register(elliptic.P256()) + + encoder := gob.NewEncoder(&content) + err := encoder.Encode(ws) + if err != nil { + logging.ErrorLogger.Printf("%v", err) + runtime.Goexit() + } + + err = ioutil.WriteFile(walletFile, content.Bytes(), 0644) + if err != nil { + logging.ErrorLogger.Printf("%v", err) + runtime.Goexit() + } +} + +func (ws *Wallets) LoadFile() error { + if _, err := os.Stat(walletFile); os.IsNotExist(err) { + return err + } + + var wallets Wallets + + fileContent, err := ioutil.ReadFile(walletFile) + if err != nil { + logging.ErrorLogger.Printf("%v", err) + runtime.Goexit() + } + + gob.Register(elliptic.P256()) + decoder := gob.NewDecoder(bytes.NewReader(fileContent)) + + err = decoder.Decode(&wallets) + if err != nil { + logging.ErrorLogger.Printf("%v", err) + runtime.Goexit() + } + + ws.Wallets = wallets.Wallets + + return nil +} + +func CreateWallets() (*Wallets, error) { + wallets := &Wallets{} + wallets.Wallets = make(map[string]*Wallet) + + err := wallets.LoadFile() + + return wallets, err +} + +func (ws *Wallets) GetWallet(address string) *Wallet { + return ws.Wallets[address] +} + +func (ws *Wallets) GetAllAddresses() []string { + var addresses []string + + for address := range ws.Wallets { + addresses = append(addresses, address) + } + + return addresses +} + +func (ws *Wallets) AddWallet() string { + wallet := NewWallet() + + address := fmt.Sprintf("%s", wallet.Address()) + + ws.Wallets[address] = wallet + + return address +}