diff --git a/.gitignore b/.gitignore index 556b3b5..12dc28f 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,6 @@ # Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 .glide/ -keystore/ client.db -bazo-client \ No newline at end of file +bazo-client +*.key \ No newline at end of file diff --git a/README.md b/README.md index 7eb0b03..4e3e9c5 100644 --- a/README.md +++ b/README.md @@ -20,10 +20,6 @@ Contents of `configuration.json`: "bootstrap_server": { "ip": "127.0.0.1", "port": "8000" - }, - "multisig_server": { - "ip": "127.0.0.1", - "port": "8020" } } ``` @@ -118,13 +114,12 @@ Options * `--from`: The file to load the sender's private key from * `--to`: The file to load the recipient's public key from * `--toAddress`: Instead of passing the recipient's address by file with `--to`, you can also directly pass the recipient's address with this option -* `--multisig`: (optional) The file to load the multisig's private key from. Examples ```bash bazo-client funds --from myaccount.txt --to recipient.txt --txcount 0 --amount 100 -bazo-client funds --from myaccount.txt --to recipient.txt --txcount 1 --amount 100 --multisig myaccount.txt +bazo-client funds --from myaccount.txt --to recipient.txt --txcount 1 --amount 100 bazo-client funds --from myaccount.txt --toAddress b978...<120 byte omitted>...e86ba --txcount 2 --amount 100 --fee 15 ``` diff --git a/REST/EPTransaction.go b/REST/EPTransaction.go index 03d4f6b..76da559 100644 --- a/REST/EPTransaction.go +++ b/REST/EPTransaction.go @@ -28,7 +28,7 @@ type Content struct { Detail interface{} `json:"detail,omitempty"` } -func CreateAccTxEndpoint(w http.ResponseWriter, req *http.Request) { +func CreateContractTxEndpoint(w http.ResponseWriter, req *http.Request) { logger.Println("Incoming createAcc request") params := mux.Vars(req) @@ -36,7 +36,7 @@ func CreateAccTxEndpoint(w http.ResponseWriter, req *http.Request) { header, _ := strconv.Atoi(params["header"]) fee, _ := strconv.Atoi(params["fee"]) - tx := protocol.AccTx{ + tx := protocol.ContractTx{ Header: byte(header), Fee: uint64(fee), } @@ -49,7 +49,7 @@ func CreateAccTxEndpoint(w http.ResponseWriter, req *http.Request) { copy(tx.PubKey[32:], newAccAddress.PublicKey.Y.Bytes()) txHash := tx.Hash() - client.UnsignedAccTx[txHash] = &tx + client.UnsignedContractTx[txHash] = &tx var content []Content content = append(content, Content{"PubKey1", hex.EncodeToString(tx.PubKey[:32])}) @@ -57,10 +57,10 @@ func CreateAccTxEndpoint(w http.ResponseWriter, req *http.Request) { content = append(content, Content{"PrivKey", hex.EncodeToString(newAccAddress.D.Bytes())}) content = append(content, Content{"TxHash", hex.EncodeToString(txHash[:])}) - SendJsonResponse(w, JsonResponse{http.StatusOK, "AccTx successfully created.", content}) + SendJsonResponse(w, JsonResponse{http.StatusOK, "ContractTx successfully created.", content}) } -func CreateAccTxEndpointWithPubKey(w http.ResponseWriter, req *http.Request) { +func CreateContractTxEndpointWithPubKey(w http.ResponseWriter, req *http.Request) { logger.Println("Incoming createAcc request") params := mux.Vars(req) @@ -68,7 +68,7 @@ func CreateAccTxEndpointWithPubKey(w http.ResponseWriter, req *http.Request) { header, _ := strconv.Atoi(params["header"]) fee, _ := strconv.Atoi(params["fee"]) - tx := protocol.AccTx{ + tx := protocol.ContractTx{ Header: byte(header), Fee: uint64(fee), } @@ -79,11 +79,11 @@ func CreateAccTxEndpointWithPubKey(w http.ResponseWriter, req *http.Request) { copy(tx.Issuer[:], issuerInt.Bytes()) txHash := tx.Hash() - client.UnsignedAccTx[txHash] = &tx + client.UnsignedContractTx[txHash] = &tx var content []Content content = append(content, Content{"TxHash", hex.EncodeToString(txHash[:])}) - SendJsonResponse(w, JsonResponse{http.StatusOK, "AccTx successfully created.", content}) + SendJsonResponse(w, JsonResponse{http.StatusOK, "ContractTx successfully created.", content}) } func CreateConfigTxEndpoint(w http.ResponseWriter, req *http.Request) { @@ -137,8 +137,8 @@ func CreateFundsTxEndpoint(w http.ResponseWriter, req *http.Request) { Amount: uint64(amount), Fee: uint64(fee), TxCnt: uint32(txCnt), - From: protocol.SerializeHashContent(fromPub), - To: protocol.SerializeHashContent(toPub), + From: fromPub, + To: toPub, } txHash := tx.Hash() @@ -166,7 +166,7 @@ func sendTxEndpoint(w http.ResponseWriter, req *http.Request, txType int) { switch txType { case p2p.ACCTX_BRDCST: - if tx := client.UnsignedAccTx[txHash]; tx != nil { + if tx := client.UnsignedContractTx[txHash]; tx != nil { tx.Sig = txSign err = network.SendTx(util.Config.BootstrapIpport, tx, p2p.ACCTX_BRDCST) @@ -189,17 +189,11 @@ func sendTxEndpoint(w http.ResponseWriter, req *http.Request, txType int) { } case p2p.FUNDSTX_BRDCST: if tx := client.UnsignedFundsTx[txHash]; tx != nil { - if tx.Sig1 == [64]byte{} { - tx.Sig1 = txSign - err = network.SendTx(util.Config.MultisigIpport, tx, p2p.FUNDSTX_BRDCST) - if err != nil { - delete(client.UnsignedFundsTx, txHash) - } - } else { - tx.Sig2 = txSign - err = network.SendTx(util.Config.BootstrapIpport, tx, p2p.FUNDSTX_BRDCST) - delete(client.UnsignedFundsTx, txHash) - } + tx.Sig = txSign + err = network.SendTx(util.Config.BootstrapIpport, tx, p2p.FUNDSTX_BRDCST) + + //If tx was successful or not, delete it from map either way. A new tx creation is the only option to repeat. + delete(client.UnsignedFundsTx, txHash) } else { logger.Printf("No transaction with hash %x found to sign\n", txHash) SendJsonResponse(w, JsonResponse{http.StatusInternalServerError, fmt.Sprintf("No transaction with hash %x found to sign", txHash), nil}) @@ -215,7 +209,7 @@ func sendTxEndpoint(w http.ResponseWriter, req *http.Request, txType int) { } } -func SendAccTxEndpoint(w http.ResponseWriter, req *http.Request) { +func SendContractTxEndpoint(w http.ResponseWriter, req *http.Request) { sendTxEndpoint(w, req, p2p.ACCTX_BRDCST) } diff --git a/REST/REST.go b/REST/REST.go index af751bf..6035c46 100644 --- a/REST/REST.go +++ b/REST/REST.go @@ -26,9 +26,9 @@ func Init() { func getEndpoints(router *mux.Router) { router.HandleFunc("/account/{id}", GetAccountEndpoint).Methods("GET") - router.HandleFunc("/createAccTx/{header}/{fee}/{issuer}", CreateAccTxEndpoint).Methods("POST") - router.HandleFunc("/createAccTx/{pubKey}/{header}/{fee}/{issuer}", CreateAccTxEndpointWithPubKey).Methods("POST") - router.HandleFunc("/sendAccTx/{txHash}/{txSign}", SendAccTxEndpoint).Methods("POST") + router.HandleFunc("/createContractTx/{header}/{fee}/{issuer}", CreateContractTxEndpoint).Methods("POST") + router.HandleFunc("/createContractTx/{pubKey}/{header}/{fee}/{issuer}", CreateContractTxEndpointWithPubKey).Methods("POST") + router.HandleFunc("/sendContractTx/{txHash}/{txSign}", SendContractTxEndpoint).Methods("POST") router.HandleFunc("/createConfigTx/{header}/{id}/{payload}/{fee}/{txCnt}", CreateConfigTxEndpoint).Methods("POST") router.HandleFunc("/sendConfigTx/{txHash}/{txSign}", SendConfigTxEndpoint).Methods("POST") diff --git a/cli/account.go b/cli/account.go index 633586f..1fbaf75 100644 --- a/cli/account.go +++ b/cli/account.go @@ -1,56 +1,87 @@ package cli import ( - "fmt" - "github.com/bazo-blockchain/bazo-client/network" - "github.com/bazo-blockchain/bazo-client/util" - "github.com/bazo-blockchain/bazo-miner/p2p" - "github.com/bazo-blockchain/bazo-miner/protocol" + "errors" + "github.com/bazo-blockchain/bazo-client/client" + "github.com/bazo-blockchain/bazo-miner/crypto" "github.com/urfave/cli" "log" + "math/big" ) -var ( - headerFlag = cli.IntFlag { - Name: "header", - Usage: "header flag", - Value: 0, - } - - feeFlag = cli.Uint64Flag { - Name: "fee", - Usage: "specify the fee", - Value: 1, - } - - rootkeyFlag = cli.StringFlag { - Name: "rootwallet", - Usage: "load root's public private key from `FILE`", - } -) +type accountArgs struct { + address string + walletFile string +} func GetAccountCommand(logger *log.Logger) cli.Command { return cli.Command { Name: "account", Usage: "account management", - Subcommands: []cli.Command { - getCheckAccountCommand(logger), - getCreateAccountCommand(logger), - getAddAccountCommand(logger), + Action: func(c *cli.Context) error { + client.Init() + + args := &accountArgs{ + address: c.String("address"), + walletFile: c.String("wallet"), + } + + return checkAccount(args, logger) + }, + Flags: []cli.Flag { + cli.StringFlag { + Name: "address", + Usage: "the account's 128 byte address", + }, + cli.StringFlag { + Name: "wallet", + Usage: "load the account's 128 byte address from `FILE`", + Value: "wallet.txt", + }, }, } } +func checkAccount(args *accountArgs, logger *log.Logger) error { + err := args.ValidateInput() + if err != nil { + return err + } + + var address [64]byte + if len(args.address) == 128 { + newPubInt, _ := new(big.Int).SetString(args.address, 16) + copy(address[:], newPubInt.Bytes()) + } else { + privKey, err := crypto.ExtractECDSAKeyFromFile(args.walletFile) + if err != nil { + logger.Printf("%v\n", err) + return err + } + address = crypto.GetAddressFromPubKey(&privKey.PublicKey) + } -func sendAccountTx(tx protocol.Transaction, logger *log.Logger) error { - fmt.Printf("chash: %x\n", tx.Hash()) + logger.Printf("My address: %x\n", address) - if err := network.SendTx(util.Config.BootstrapIpport, tx, p2p.ACCTX_BRDCST); err != nil { - logger.Printf("%v\n", err) + acc, _, err := client.CheckAccount(address) + if err != nil { + logger.Println(err) return err } else { - logger.Printf("Transaction successfully sent to network:\nTxHash: %x%v", tx.Hash(), tx) + logger.Printf(acc.String()) + } + + return nil +} + +func (args accountArgs) ValidateInput() error { + if len(args.address) == 0 && len(args.walletFile) == 0 { + return errors.New("argument missing: address or wallet") + } + + if len(args.walletFile) == 0 && len(args.address) != 128 { + return errors.New("invalid argument: address") } return nil diff --git a/cli/add.go b/cli/add.go deleted file mode 100644 index 15c9ada..0000000 --- a/cli/add.go +++ /dev/null @@ -1,86 +0,0 @@ -package cli - -import ( - "errors" - "github.com/bazo-blockchain/bazo-miner/crypto" - "github.com/bazo-blockchain/bazo-miner/protocol" - "github.com/urfave/cli" - "log" - "math/big" -) - -type addAccountArgs struct { - header int - fee uint64 - rootWalletFile string - address string -} - -func getAddAccountCommand(logger *log.Logger) cli.Command { - return cli.Command { - Name: "add", - Usage: "add an existing account", - Action: func(c *cli.Context) error { - args := &addAccountArgs { - header: c.Int("header"), - fee: c.Uint64("fee"), - rootWalletFile: c.String("rootwallet"), - address: c.String("address"), - } - - return addAccount(args, logger) - }, - Flags: []cli.Flag { - headerFlag, - feeFlag, - rootkeyFlag, - cli.StringFlag { - Name: "address", - Usage: "the account's address", - }, - }, - } -} - -func addAccount(args *addAccountArgs, logger *log.Logger) error { - err := args.ValidateInput() - if err != nil { - return err - } - - privKey, err := crypto.ExtractECDSAKeyFromFile(args.rootWalletFile) - if err != nil { - return err - } - - var newAddress [64]byte - newPubInt, _ := new(big.Int).SetString(args.address, 16) - copy(newAddress[:], newPubInt.Bytes()) - - tx, _, err := protocol.ConstrAccTx(byte(args.header), uint64(args.fee), newAddress, privKey, nil, nil) - if err != nil { - return err - } - - return sendAccountTx(tx, logger) -} - -func (args addAccountArgs) ValidateInput() error { - if args.fee <= 0 { - return errors.New("invalid argument: fee must be > 0") - } - - if len(args.rootWalletFile) == 0 { - return errors.New("argument missing: rootwallet") - } - - if len(args.address) == 0 { - return errors.New("argument missing: address") - } - - if len(args.address) != 128 { - return errors.New("invalid argument length: address") - } - - return nil -} \ No newline at end of file diff --git a/cli/check.go b/cli/check.go deleted file mode 100644 index adc9c7d..0000000 --- a/cli/check.go +++ /dev/null @@ -1,86 +0,0 @@ -package cli - -import ( - "errors" - "github.com/bazo-blockchain/bazo-client/client" - "github.com/bazo-blockchain/bazo-miner/crypto" - "github.com/urfave/cli" - "log" - "math/big" -) - -type checkAccountArgs struct { - address string - walletFile string -} - -func getCheckAccountCommand(logger *log.Logger) cli.Command { - return cli.Command { - Name: "check", - Usage: "check account state", - Action: func(c *cli.Context) error { - args := &checkAccountArgs { - address: c.String("address"), - walletFile: c.String("wallet"), - } - - return checkAccount(args, logger) - }, - Flags: []cli.Flag { - cli.StringFlag { - Name: "address", - Usage: "the account's 128 byte address", - }, - cli.StringFlag { - Name: "wallet", - Usage: "load the account's 128 byte address from `FILE`", - Value: "wallet.txt", - }, - }, - } -} - -func checkAccount(args *checkAccountArgs, logger *log.Logger) error { - err := args.ValidateInput() - if err != nil { - return err - } - - var address [64]byte - if len(args.address) == 128 { - newPubInt, _ := new(big.Int).SetString(args.address, 16) - copy(address[:], newPubInt.Bytes()) - } else { - privKey, err := crypto.ExtractECDSAKeyFromFile(args.walletFile) - if err != nil { - logger.Printf("%v\n", err) - return err - } - - address = crypto.GetAddressFromPubKey(&privKey.PublicKey) - } - - logger.Printf("My address: %x\n", address) - - acc, _, err := client.CheckAccount(address) - if err != nil { - logger.Println(err) - return err - } else { - logger.Printf(acc.String()) - } - - return nil -} - -func (args checkAccountArgs) ValidateInput() error { - if len(args.address) == 0 && len(args.walletFile) == 0 { - return errors.New("argument missing: address or wallet") - } - - if len(args.walletFile) == 0 && len(args.address) != 128 { - return errors.New("invalid argument: address") - } - - return nil -} \ No newline at end of file diff --git a/cli/create.go b/cli/create.go deleted file mode 100644 index 9070020..0000000 --- a/cli/create.go +++ /dev/null @@ -1,95 +0,0 @@ -package cli - -import ( - "crypto/ecdsa" - "errors" - "fmt" - "github.com/bazo-blockchain/bazo-miner/crypto" - "github.com/bazo-blockchain/bazo-miner/protocol" - "github.com/urfave/cli" - "log" - "os" -) - -type createAccountArgs struct { - header int - fee uint64 - rootWalletFile string - walletFile string -} - -func getCreateAccountCommand(logger *log.Logger) cli.Command { - return cli.Command { - Name: "create", - Usage: "create a new account and add it to the network", - Action: func(c *cli.Context) error { - args := &createAccountArgs { - header: c.Int("header"), - fee: c.Uint64("fee"), - rootWalletFile: c.String("rootwallet"), - walletFile: c.String("wallet"), - } - - return createAccount(args, logger) - }, - Flags: []cli.Flag { - headerFlag, - feeFlag, - rootkeyFlag, - cli.StringFlag { - Name: "wallet", - Usage: "save new account's public private key to `FILE`", - }, - }, - } -} - -func createAccount(args *createAccountArgs, logger *log.Logger) error { - err := args.ValidateInput() - if err != nil { - return err - } - - privKey, err := crypto.ExtractECDSAKeyFromFile(args.rootWalletFile) - if err != nil { - return err - } - - var newKey *ecdsa.PrivateKey - //Write the public key to the given textfile - file, err := os.Create(args.walletFile) - if err != nil { - return err - } - - tx, newKey, err := protocol.ConstrAccTx(byte(args.header), uint64(args.fee), [64]byte{}, privKey, nil, nil) - if err != nil { - return err - } - - _, err = file.WriteString(string(newKey.X.Text(16)) + "\n") - _, err = file.WriteString(string(newKey.Y.Text(16)) + "\n") - _, err = file.WriteString(string(newKey.D.Text(16)) + "\n") - - if err != nil { - return errors.New(fmt.Sprintf("failed to write key to file %v", args.walletFile)) - } - - return sendAccountTx(tx, logger) -} - -func (args createAccountArgs) ValidateInput() error { - if args.fee <= 0 { - return errors.New("invalid argument: fee must be > 0") - } - - if len(args.rootWalletFile) == 0 { - return errors.New("argument missing: rootWalletFile") - } - - if len(args.walletFile) == 0 { - return errors.New("argument missing: walletFile") - } - - return nil -} \ No newline at end of file diff --git a/cli/funds.go b/cli/funds.go index 5b554e5..7940057 100644 --- a/cli/funds.go +++ b/cli/funds.go @@ -4,6 +4,7 @@ import ( "crypto/ecdsa" "errors" "fmt" + "github.com/bazo-blockchain/bazo-client/client" "github.com/bazo-blockchain/bazo-client/network" "github.com/bazo-blockchain/bazo-client/util" "github.com/bazo-blockchain/bazo-miner/crypto" @@ -18,7 +19,6 @@ type fundsArgs struct { fromWalletFile string toWalletFile string toAddress string - multisigFile string amount uint64 fee uint64 txcount int @@ -29,12 +29,13 @@ func GetFundsCommand(logger *log.Logger) cli.Command { Name: "funds", Usage: "send funds from one account to another", Action: func(c *cli.Context) error { + client.Init() + args := &fundsArgs{ header: c.Int("header"), fromWalletFile: c.String("from"), toWalletFile: c.String("to"), toAddress: c.String("toAddress"), - multisigFile: c.String("multisig"), amount: c.Uint64("amount"), fee: c.Uint64("fee"), txcount: c.Int("txcount"), @@ -73,10 +74,6 @@ func GetFundsCommand(logger *log.Logger) cli.Command { Name: "txcount", Usage: "the sender's current transaction counter", }, - cli.StringFlag { - Name: "multisig", - Usage: "load multi-signature server’s private key from `FILE`", - }, }, } } @@ -117,16 +114,6 @@ func sendFunds(args *fundsArgs, logger *log.Logger) error { } } - var multisigPrivKey *ecdsa.PrivateKey - if len(args.multisigFile) > 0 { - multisigPrivKey, err = crypto.ExtractECDSAKeyFromFile(args.multisigFile) - if err != nil { - return err - } - } else { - multisigPrivKey = fromPrivKey - } - fromAddress := crypto.GetAddressFromPubKey(&fromPrivKey.PublicKey) toAddress := crypto.GetAddressFromPubKey(toPubKey) @@ -135,10 +122,9 @@ func sendFunds(args *fundsArgs, logger *log.Logger) error { uint64(args.amount), uint64(args.fee), uint32(args.txcount), - protocol.SerializeHashContent(fromAddress), - protocol.SerializeHashContent(toAddress), + fromAddress, + toAddress, fromPrivKey, - multisigPrivKey, nil) if err != nil { diff --git a/cli/network.go b/cli/network.go index c3614ed..40eb766 100644 --- a/cli/network.go +++ b/cli/network.go @@ -2,6 +2,7 @@ package cli import ( "errors" + "github.com/bazo-blockchain/bazo-client/client" "github.com/bazo-blockchain/bazo-client/network" "github.com/bazo-blockchain/bazo-client/util" "github.com/bazo-blockchain/bazo-miner/crypto" @@ -39,6 +40,8 @@ func GetNetworkCommand(logger *log.Logger) cli.Command { Name: "network", Usage: "configure the network", Action: func(c *cli.Context) error { + client.Init() + optionsSetByUser := 0 for _, option := range options { if !c.IsSet(option.name) { continue } diff --git a/cli/staking.go b/cli/staking.go index 9c34a59..39709d3 100644 --- a/cli/staking.go +++ b/cli/staking.go @@ -3,6 +3,7 @@ package cli import ( "crypto/rsa" "errors" + "github.com/bazo-blockchain/bazo-client/client" "github.com/bazo-blockchain/bazo-client/network" "github.com/bazo-blockchain/bazo-client/util" "github.com/bazo-blockchain/bazo-miner/crypto" @@ -47,6 +48,8 @@ func GetStakingCommand(logger *log.Logger) cli.Command { Name: "enable", Usage: "join the pool of validators", Action: func(c *cli.Context) error { + client.Init() + args := parseStakingArgs(c) args.stakingValue = true return toggleStaking(args, logger) @@ -66,6 +69,8 @@ func GetStakingCommand(logger *log.Logger) cli.Command { Name: "disable", Usage: "leave the pool of validators", Action: func(c *cli.Context) error { + client.Init() + args := parseStakingArgs(c) args.stakingValue = false return toggleStaking(args, logger) @@ -115,7 +120,7 @@ func toggleStaking(args *stakingArgs, logger *log.Logger) error { byte(args.header), uint64(args.fee), args.stakingValue, - protocol.SerializeHashContent(accountPubKey), + accountPubKey, privKey, commPubKey, ) diff --git a/client/account.go b/client/account.go index 7931cf3..b4e21f8 100644 --- a/client/account.go +++ b/client/account.go @@ -37,7 +37,6 @@ func GetAccount(address [64]byte) (*Account, []*FundsTxJson, error) { account.IsCreated = true account.IsStaking = acc.IsStaking - //If Acc is Root in the bazo network state, we do not check for accTx, else we check network.AccReq(true, protocol.SerializeHashContent(account.Address)) if rootAccI, _ := network.Fetch(network.AccChan); rootAccI != nil { if rootAcc := rootAccI.(*protocol.Account); rootAcc != nil { @@ -61,7 +60,6 @@ func GetAccount(address [64]byte) (*Account, []*FundsTxJson, error) { return nil, nil, errors.New(fmt.Sprintf("Could not calculate state of account %x: %v\n", account.Address[:8], err)) } - //No accTx exists for this account since it is the initial root account //Add the initial root's balance //if account.IsCreated == false && account.IsRoot == true { // account.IsCreated = true diff --git a/client/evaluate.go b/client/evaluate.go index ecf3453..088a5ec 100644 --- a/client/evaluate.go +++ b/client/evaluate.go @@ -25,13 +25,13 @@ func getRelevantBlocks(relevantBlockHeaders []*protocol.Block) (relevantBlocks [ return relevantBlocks, nil } -func getRelevantBlockHeaders(pubKeyHash [32]byte) (relevantHeadersBeneficiary []*protocol.Block, relevantHeadersConfigBF []*protocol.Block) { +func getRelevantBlockHeaders(pubKey [64]byte) (relevantHeadersBeneficiary []*protocol.Block, relevantHeadersConfigBF []*protocol.Block) { for _, blockHeader := range blockHeaders { - if blockHeader.Beneficiary == pubKeyHash { + if blockHeader.Beneficiary == pubKey { relevantHeadersBeneficiary = append(relevantHeadersBeneficiary, blockHeader) } - if blockHeader.NrConfigTx > 0 || (blockHeader.NrElementsBF > 0 && blockHeader.BloomFilter.Test(pubKeyHash[:])) { + if blockHeader.NrConfigTx > 0 || (blockHeader.NrElementsBF > 0 && blockHeader.BloomFilter.Test(pubKey[:])) { relevantHeadersConfigBF = append(relevantHeadersConfigBF, blockHeader) } } diff --git a/client/fundsTxJson.go b/client/fundsTxJson.go index 0bc364d..60df4f1 100644 --- a/client/fundsTxJson.go +++ b/client/fundsTxJson.go @@ -13,8 +13,7 @@ type FundsTxJson struct { TxCnt uint32 `json:"txCnt"` From string `json:"from"` To string `json:"to"` - Sig1 string `json:"sig1"` - Sig2 string `json:"sig2"` + Sig string `json:"sig"` Status string `json:"status"` } @@ -28,8 +27,7 @@ func ConvertFundsTx(fundsTx *protocol.FundsTx, status string) (fundsTxJson *Fund fundsTx.TxCnt, hex.EncodeToString(fundsTx.From[:]), hex.EncodeToString(fundsTx.To[:]), - hex.EncodeToString(fundsTx.Sig1[:]), - hex.EncodeToString(fundsTx.Sig2[:]), + hex.EncodeToString(fundsTx.Sig[:]), status, } } diff --git a/client/state.go b/client/state.go index d1e9152..05e046a 100644 --- a/client/state.go +++ b/client/state.go @@ -15,7 +15,7 @@ var ( activeParameters miner.Parameters - UnsignedAccTx = make(map[[32]byte]*protocol.AccTx) + UnsignedContractTx = make(map[[32]byte]*protocol.ContractTx) UnsignedConfigTx = make(map[[32]byte]*protocol.ConfigTx) UnsignedFundsTx = make(map[[32]byte]*protocol.FundsTx) ) @@ -162,15 +162,13 @@ func saveAndLogBlockHeader(blockHeader *protocol.Block) { } func getState(acc *Account, lastTenTx []*FundsTxJson) (err error) { - pubKeyHash := protocol.SerializeHashContent(acc.Address) //Get blocks if the Acc address: - //* got issued as an Acc //* sent funds //* received funds //* is block's beneficiary //* nr of configTx in block is > 0 (in order to maintain params in light-client) - relevantHeadersBeneficiary, relevantHeadersConfigBF := getRelevantBlockHeaders(pubKeyHash) + relevantHeadersBeneficiary, relevantHeadersConfigBF := getRelevantBlockHeaders(acc.Address) acc.Balance += activeParameters.Block_reward * uint64(len(relevantHeadersBeneficiary)) @@ -192,13 +190,13 @@ func getState(acc *Account, lastTenTx []*FundsTxJson) (err error) { tx := txI.(protocol.Transaction) fundsTx := txI.(*protocol.FundsTx) - if fundsTx.From == pubKeyHash || fundsTx.To == pubKeyHash || block.Beneficiary == pubKeyHash { + if fundsTx.From == acc.Address || fundsTx.To == acc.Address || block.Beneficiary == acc.Address { //Validate tx if err := validateTx(block, tx, txHash); err != nil { return err } - if fundsTx.From == pubKeyHash { + if fundsTx.From == acc.Address { //If Acc is no root, balance funds if !acc.IsRoot { acc.Balance -= fundsTx.Amount @@ -208,49 +206,18 @@ func getState(acc *Account, lastTenTx []*FundsTxJson) (err error) { acc.TxCnt += 1 } - if fundsTx.To == pubKeyHash { + if fundsTx.To == acc.Address { acc.Balance += fundsTx.Amount put(lastTenTx, ConvertFundsTx(fundsTx, "verified")) } - if block.Beneficiary == pubKeyHash { + if block.Beneficiary == acc.Address { acc.Balance += fundsTx.Fee } } } - //Check if Account was issued and collect fee - //for _, txHash := range block.AccTxData { - // err := network.TxReq(p2p.ACCTX_REQ, txHash) - // if err != nil { - // return err - // } - // - // txI, err := network.Fetch(network.AccTxChan) - // if err != nil { - // return err - // } - // - // tx := txI.(protocol.Transaction) - // accTx := txI.(*protocol.AccTx) - // - // if accTx.PubKey == acc.Address || block.Beneficiary == pubKeyHash { - // //Validate tx - // if err := validateTx(block, tx, txHash); err != nil { - // return err - // } - // - // if accTx.PubKey == acc.Address { - // acc.IsCreated = true - // } - // - // if block.Beneficiary == pubKeyHash { - // acc.Balance += accTx.Fee - // } - // } - //} - //Update config parameters and collect fee for _, txHash := range block.ConfigTxData { err := network.TxReq(p2p.CONFIGTX_REQ, txHash) @@ -268,7 +235,7 @@ func getState(acc *Account, lastTenTx []*FundsTxJson) (err error) { configTxSlice := []*protocol.ConfigTx{configTx} - if block.Beneficiary == pubKeyHash { + if block.Beneficiary == acc.Address { //Validate tx if err := validateTx(block, tx, txHash); err != nil { return err @@ -285,15 +252,5 @@ func getState(acc *Account, lastTenTx []*FundsTxJson) (err error) { } } - addressHash := protocol.SerializeHashContent(acc.Address) - for _, tx := range network.NonVerifiedTxReq(addressHash) { - if tx.To == addressHash { - put(lastTenTx, ConvertFundsTx(tx, "not verified")) - } - if tx.From == addressHash { - acc.TxCnt++ - } - } - return nil } diff --git a/client/util.go b/client/util.go index 897f695..33a0330 100644 --- a/client/util.go +++ b/client/util.go @@ -1,7 +1,10 @@ package client import ( + "github.com/bazo-blockchain/bazo-client/cstorage" + "github.com/bazo-blockchain/bazo-client/network" "github.com/bazo-blockchain/bazo-client/util" + "github.com/bazo-blockchain/bazo-miner/p2p" "log" ) @@ -9,8 +12,14 @@ var ( logger *log.Logger ) -func InitLogging() { +func Init() { + p2p.InitLogging() logger = util.InitLogger() + + util.Config = util.LoadConfiguration() + + network.Init() + cstorage.Init("client.db") } func put(slice []*FundsTxJson, tx *FundsTxJson) { diff --git a/configuration.json b/configuration.json index 8337c82..137d66b 100644 --- a/configuration.json +++ b/configuration.json @@ -6,9 +6,5 @@ "bootstrap_server": { "ip": "127.0.0.1", "port": "8000" - }, - "multisig_server": { - "ip": "127.0.0.1", - "port": "8020" } } \ No newline at end of file diff --git a/main.go b/main.go index c21c9eb..51d69cb 100644 --- a/main.go +++ b/main.go @@ -2,23 +2,13 @@ package main import ( "github.com/bazo-blockchain/bazo-client/cli" - "github.com/bazo-blockchain/bazo-client/client" - "github.com/bazo-blockchain/bazo-client/cstorage" - "github.com/bazo-blockchain/bazo-client/network" "github.com/bazo-blockchain/bazo-client/util" - "github.com/bazo-blockchain/bazo-miner/p2p" cli2 "github.com/urfave/cli" "os" ) func main() { - p2p.InitLogging() - client.InitLogging() logger := util.InitLogger() - util.Config = util.LoadConfiguration() - - network.Init() - cstorage.Init("client.db") app := cli2.NewApp() diff --git a/network/incoming.go b/network/incoming.go index 0766cff..542256a 100644 --- a/network/incoming.go +++ b/network/incoming.go @@ -13,7 +13,7 @@ var ( BlockChan = make(chan interface{}) BlockHeaderChan = make(chan interface{}) FundsTxChan = make(chan interface{}) - AccTxChan = make(chan interface{}) + ContractTxChan = make(chan interface{}) ConfigTxChan = make(chan interface{}) StakeTxChan = make(chan interface{}) AccChan = make(chan interface{}) @@ -38,8 +38,8 @@ func processIncomingMsg(p *peer, header *p2p.Header, payload []byte) { blockHeaderRes(p, payload) case p2p.FUNDSTX_RES: txRes(p, payload, p2p.FUNDSTX_RES) - case p2p.ACCTX_RES: - txRes(p, payload, p2p.ACCTX_RES) + case p2p.CONTRACTTX_RES: + txRes(p, payload, p2p.CONTRACTTX_RES) case p2p.CONFIGTX_RES: txRes(p, payload, p2p.CONFIGTX_RES) case p2p.STAKETX_RES: diff --git a/network/requests.go b/network/requests.go index 92c30b1..f848118 100644 --- a/network/requests.go +++ b/network/requests.go @@ -3,7 +3,6 @@ package network import ( "errors" "fmt" - "github.com/bazo-blockchain/bazo-client/util" "github.com/bazo-blockchain/bazo-miner/p2p" "github.com/bazo-blockchain/bazo-miner/protocol" ) @@ -80,26 +79,6 @@ func SendTx(dial string, tx protocol.Transaction, typeID uint8) (err error) { return errors.New(fmt.Sprintf("Sending tx %x failed.", txHash[:8])) } -func NonVerifiedTxReq(addressHash [32]byte) (nonVerifiedTxs []*protocol.FundsTx) { - if conn := p2p.Connect(util.Config.MultisigIpport); conn != nil { - packet := p2p.BuildPacket(p2p.FUNDSTX_REQ, addressHash[:]) - conn.Write(packet) - - header, payload, err := p2p.RcvData_(conn) - if err != nil || header.TypeID != p2p.FUNDSTX_RES { - logger.Printf("Requesting non verified tx failed.") - return nil - } - - for _, data := range protocol.Decode(payload, protocol.FUNDSTX_SIZE) { - var tx *protocol.FundsTx - nonVerifiedTxs = append(nonVerifiedTxs, tx.Decode(data)) - } - } - - return nonVerifiedTxs -} - func IntermediateNodesReq(blockHash [32]byte, txHash [32]byte) error { p := peers.getRandomPeer() if p == nil { diff --git a/network/responses.go b/network/responses.go index 29f7709..dd11ba1 100644 --- a/network/responses.go +++ b/network/responses.go @@ -38,13 +38,13 @@ func txRes(p *peer, payload []byte, txType uint8) { return } FundsTxChan <- fundsTx - case p2p.ACCTX_RES: - var accTx *protocol.AccTx - accTx = accTx.Decode(payload) - if accTx == nil { + case p2p.CONTRACTTX_RES: + var contractTx *protocol.ContractTx + contractTx = contractTx.Decode(payload) + if contractTx == nil { return } - AccTxChan <- accTx + ContractTxChan <- contractTx case p2p.CONFIGTX_RES: var configTx *protocol.ConfigTx configTx = configTx.Decode(payload) diff --git a/util/config.go b/util/config.go index b681d22..1835545 100644 --- a/util/config.go +++ b/util/config.go @@ -29,11 +29,6 @@ type Configuration struct { Ip string `json:"ip"` Port string `json:"port"` } `json:"bootstrap_server"` - MultisigIpport string - Multisigserver struct { - Ip string `json:"ip"` - Port string `json:"port"` - } `json:"multisig_server"` } func LoadConfiguration() (config Configuration) { @@ -47,6 +42,5 @@ func LoadConfiguration() (config Configuration) { config.ThisIpport = config.Thisclient.Ip + ":" + config.Thisclient.Port config.BootstrapIpport = config.Bootstrapserver.Ip + ":" + config.Bootstrapserver.Port - config.MultisigIpport = config.Multisigserver.Ip + ":" + config.Multisigserver.Port return config }