func (AddInput) Execute(state IState, args []string) error { if len(args) != 4 { return fmt.Errorf("Invalid Parameters") } key := args[1] adr := args[2] amt := args[3] ib := state.GetFS().GetDB().GetRaw([]byte(fct.DB_BUILD_TRANS), []byte(key)) trans, ok := ib.(fct.ITransaction) if ib == nil || !ok { return fmt.Errorf("Unknown Transaction: " + key) } var addr fct.IAddress if !fct.ValidateFUserStr(adr) { if len(adr) != 64 { if len(adr) > 32 { return fmt.Errorf("Invalid Name. Check the address or name for proper entry.", len(adr)) } we := state.GetFS().GetDB().GetRaw([]byte(fct.W_NAME), []byte(adr)) if we != nil { we2 := we.(wallet.IWalletEntry) addr, _ = we2.GetAddress() adr = hex.EncodeToString(addr.Bytes()) } else { return fmt.Errorf("Name is undefined.") } } else { badr, err := hex.DecodeString(adr) if err != nil { return fmt.Errorf("Looks like an Invalid hex address. Check that you entered it correctly") } addr = fct.NewAddress(badr) } } else { fmt.Printf("adr: %x\n", adr) addr = fct.NewAddress(fct.ConvertUserStrToAddress(adr)) } amount, _ := fct.ConvertFixedPoint(amt) bamount, _ := strconv.ParseInt(amount, 10, 64) err := state.GetFS().GetWallet().AddInput(trans, addr, uint64(bamount)) if err != nil { return err } fmt.Println("Added Input of ", amt, " to be paid from ", args[2], fct.ConvertFctAddressToUserStr(addr)) return nil }
func handleFactoidBalance(ctx *web.Context, eckey string) { type fbal struct { Response string Success bool } var b fbal adr, err := hex.DecodeString(eckey) if err == nil && len(adr) != common.HASH_LENGTH { b = fbal{Response: "Invalid Address", Success: false} } if err == nil { v := int64(common.FactoidState.GetBalance(fct.NewAddress(adr))) str := fmt.Sprintf("%d", v) b = fbal{Response: str, Success: true} } else { b = fbal{Response: err.Error(), Success: false} } if p, err := json.Marshal(b); err != nil { wsLog.Error(err) return } else { ctx.Write(p) } }
func Test_Address(test *testing.T) { b, _ := hex.DecodeString("8cba3aeb7d16269da4f37d0c98979a7d9b23943774be232e817504ec8ab7e2a7") adr := fct.NewAddress(b) str := fct.ConvertFctAddressToUserStr(adr) fmt.Println(str) }
func main() { privatekey := make([]byte, 32) _, err := rand.Read(privatekey) if err == nil { privAddr := factoid.NewAddress(privatekey) privHuman := factoid.ConvertFctPrivateToUserStr(privAddr) fmt.Printf("New Factoid Private Key: %v\n", privHuman) pub, priv, err := wallet.GenerateKeyFromPrivateKey(privatekey) if err != nil { panic(err) } we := new(wallet.WalletEntry) we.AddKey(pub, priv) we.SetName([]byte("test")) we.SetRCD(factoid.NewRCD_1(pub)) we.SetType("fct") address, _ := we.GetAddress() adr := factoid.ConvertFctAddressToUserStr(address) fmt.Printf("New Factoid Address: %v\n", adr) } else { fmt.Printf("error\n") } }
func SilentAddInput(txKey string, inputAddress string, inputSize string) error { ib := myState.GetFS().GetDB().GetRaw([]byte(fct.DB_BUILD_TRANS), []byte(txKey)) trans, ok := ib.(fct.ITransaction) if ib == nil || !ok { return fmt.Errorf("Unknown Transaction: " + txKey) } var addr fct.IAddress if !fct.ValidateFUserStr(inputAddress) { if len(inputAddress) != 64 { if len(inputAddress) > 32 { return fmt.Errorf("Invalid Name. Check the address or name for proper entry.", len(inputAddress)) } we := myState.GetFS().GetDB().GetRaw([]byte(fct.W_NAME), []byte(inputAddress)) if we != nil { we2 := we.(wallet.IWalletEntry) addr, _ = we2.GetAddress() inputAddress = hex.EncodeToString(addr.Bytes()) } else { return fmt.Errorf("Name is undefined.") } } else { badr, err := hex.DecodeString(inputAddress) if err != nil { return fmt.Errorf("Looks like an Invalid hex address. Check that you entered it correctly.") } addr = fct.NewAddress(badr) } } else { //fmt.Printf("adr: %x\n",adr) addr = fct.NewAddress(fct.ConvertUserStrToAddress(inputAddress)) } amount, _ := fct.ConvertFixedPoint(inputSize) bamount, _ := strconv.ParseInt(amount, 10, 64) err := myState.GetFS().GetWallet().AddInput(trans, addr, uint64(bamount)) if err != nil { return err } return nil }
// ExportKey <name> func (ExportKey) Execute(state IState, args []string) error { if len(args) != 2 { return fmt.Errorf("Invalid Parameters") } name := args[1] weblk := state.GetFS().GetDB().GetRaw([]byte(fct.W_NAME), []byte(name)) if weblk == nil { return fmt.Errorf("Unknown address. Check that you spelled the name correctly") } we := weblk.(wallet.IWalletEntry) public, err := we.GetAddress() if err != nil { return err } private := we.GetPrivKey(0) adrtype := we.GetType() binPublic := hex.EncodeToString(public.Bytes()) binPrivate := hex.EncodeToString(private[:32]) var usrPublic, usrPrivate string if adrtype == "fct" { usrPublic = fct.ConvertFctAddressToUserStr(fct.NewAddress(public.Bytes())) usrPrivate = fct.ConvertFctPrivateToUserStr(fct.NewAddress(private[:32])) } else { usrPublic = fct.ConvertECAddressToUserStr(fct.NewAddress(public.Bytes())) usrPrivate = fct.ConvertECPrivateToUserStr(fct.NewAddress(private[:32])) } fmt.Println("Private Key:") fmt.Println(" ", usrPrivate) fmt.Println(" ", binPrivate) fmt.Println("Public Key:") fmt.Println(" ", usrPublic) fmt.Println(" ", binPublic) return nil }
// Re-calculate Entry Credit Balance Map with a new Entry Credit Block func initializeECreditMap(block *common.ECBlock) { for _, entry := range block.Body.Entries { // Only process: ECIDChainCommit, ECIDEntryCommit, ECIDBalanceIncrease switch entry.ECID() { case common.ECIDChainCommit: e := entry.(*common.CommitChain) eCreditMap[string(e.ECPubKey[:])] -= int32(e.Credits) common.FactoidState.UpdateECBalance(fct.NewAddress(e.ECPubKey[:]), int64(e.Credits)) case common.ECIDEntryCommit: e := entry.(*common.CommitEntry) eCreditMap[string(e.ECPubKey[:])] -= int32(e.Credits) common.FactoidState.UpdateECBalance(fct.NewAddress(e.ECPubKey[:]), int64(e.Credits)) case common.ECIDBalanceIncrease: e := entry.(*common.IncreaseBalance) eCreditMap[string(e.ECPubKey[:])] += int32(e.NumEC) // Don't add the Increases to Factoid state, the Factoid processing will do that. case common.ECIDServerIndexNumber: case common.ECIDMinuteNumber: default: panic("Unknow entry type:" + string(entry.ECID()) + " for ECBlock:" + strconv.FormatUint(uint64(block.Header.EBHeight), 10)) } } }
func SilentAddECOutput(txKey string, outputAddress string, outputSize string) error { ib := myState.GetFS().GetDB().GetRaw([]byte(fct.DB_BUILD_TRANS), []byte(txKey)) trans, ok := ib.(fct.ITransaction) if ib == nil || !ok { return fmt.Errorf("Unknown Transaction") } var addr fct.IAddress if !fct.ValidateECUserStr(outputAddress) { if len(outputAddress) != 64 { if len(outputAddress) > 32 { return fmt.Errorf("Invalid Address or Name. Check that you entered it correctly.") } we := myState.GetFS().GetDB().GetRaw([]byte(fct.W_NAME), []byte(outputAddress)) if we != nil { we2 := we.(wallet.IWalletEntry) addr, _ = we2.GetAddress() outputAddress = hex.EncodeToString(addr.Bytes()) } else { return fmt.Errorf("Name is undefined.") } } else { if badHexChar.FindStringIndex(outputAddress) != nil { return fmt.Errorf("Looks like an invalid hex address. Check that you entered it correctly.") } } } else { addr = fct.NewAddress(fct.ConvertUserStrToAddress(outputAddress)) } amount, _ := fct.ConvertFixedPoint(outputSize) bamount, _ := strconv.ParseInt(amount, 10, 64) err := myState.GetFS().GetWallet().AddECOutput(trans, addr, uint64(bamount)) if err != nil { return err } return nil }
func (w *SCWallet) SignInputs(trans fct.ITransaction) (bool, error) { data, err := trans.MarshalBinarySig() // Get the part of the transaction we sign if err != nil { return false, err } var errMsg []byte rcds := trans.GetRCDs() for i, rcd := range rcds { rcd1, ok := rcd.(*fct.RCD_1) if ok { pub := rcd1.GetPublicKey() we, ok := w.db.GetRaw([]byte(fct.W_ADDRESS_PUB_KEY), pub).(*WalletEntry) if ok { var pri [fct.SIGNATURE_LENGTH]byte copy(pri[:], we.private[0]) bsig := ed25519.Sign(&pri, data) sig := new(fct.Signature) sig.SetSignature(bsig[:]) sigblk := new(fct.SignatureBlock) sigblk.AddSignature(sig) trans.SetSignatureBlock(i, sigblk) } else { errMsg = append(errMsg, []byte("Do not have the private key for: "+ fct.ConvertFctAddressToUserStr(fct.NewAddress(pub))+"\n")...) } } } if errMsg != nil { return false, fmt.Errorf("%s", string(errMsg)) } return true, nil }
func (AddFee) Execute(state IState, args []string) (err error) { if len(args) != 3 && len(args) != 4 { return fmt.Errorf("Invalid Parameters") } key := args[1] adr := args[2] rate := int64(0) if len(args) == 4 { srate, err := fct.ConvertFixedPoint(args[3]) if err != nil { return fmt.Errorf("Could not parse exchange rate: %v", err) } rate, err = strconv.ParseInt(srate, 10, 64) } else { if rate, err = GetRate(state); err != nil { return fmt.Errorf("Could not reach the server to get the exchange rate") } } ib := state.GetFS().GetDB().GetRaw([]byte(fct.DB_BUILD_TRANS), []byte(key)) trans, ok := ib.(fct.ITransaction) if ib == nil || !ok { return fmt.Errorf("Unknown Transaction") } var addr fct.IAddress if fct.ValidateFUserStr(adr) { addr = fct.NewAddress(fct.ConvertUserStrToAddress(adr)) } else if Utility.IsValidHexAddress(adr) { badr, _ := hex.DecodeString(adr) addr = fct.NewAddress(badr) } else if Utility.IsValidNickname(adr) { we := state.GetFS().GetDB().GetRaw([]byte(fct.W_NAME), []byte(adr)) if we != nil { we2 := we.(wallet.IWalletEntry) addr, _ = we2.GetAddress() adr = hex.EncodeToString(addr.Bytes()) } else { return fmt.Errorf("Name is undefined.") } } fee, err := trans.CalculateFee(uint64(rate)) var tin, tout, tec uint64 if tin, err = trans.TotalInputs(); err != nil { return err } if tout, err = trans.TotalOutputs(); err != nil { return err } if tec, err = trans.TotalECs(); err != nil { return err } if tin != tout+tec { msg := fmt.Sprintf("%s Total Inputs\n", fct.ConvertDecimal(tin)) msg += fmt.Sprintf("%s Total Outputs and Entry Credits\n", fct.ConvertDecimal(tout+tec)) msg += fmt.Sprintf("\nThe Inputs must match the outputs to use AddFee to add the fee to an input") return fmt.Errorf(msg) } for _, input := range trans.GetInputs() { if bytes.Equal(input.GetAddress().Bytes(), addr.Bytes()) { input.SetAmount(input.GetAmount() + fee) fmt.Printf("Added fee of %v\n", strings.TrimSpace(fct.ConvertDecimal(fee))) break } } return nil }
func loadTx(w http.ResponseWriter, r *http.Request) { ajax_post_data := r.FormValue("ajax_post_data") txName := r.FormValue("txName") if len(ajax_post_data) > 0 { loadFeedString := []string{"Import", string(txName), string(ajax_post_data)} loadErr := myState.Execute(loadFeedString) if loadErr != nil { w.Write([]byte(loadErr.Error())) return } } ib := myState.GetFS().GetDB().GetRaw([]byte(fct.DB_BUILD_TRANS), []byte(txName)) jib, jerr := json.Marshal(ib) var dat map[string]interface{} if err := json.Unmarshal(jib, &dat); err != nil { panic(err) } //fmt.Printf("%+v", dat) if dat["Inputs"] != nil { inputObjects := dat["Inputs"].([]interface{}) myInps := make([]inputList, len(inputObjects)) if len(inputObjects) > 0 { currInput := inputObjects[0].(map[string]interface{}) for i := range inputObjects { currInput = inputObjects[i].(map[string]interface{}) decodeAddr, hexErr := hex.DecodeString(currInput["Address"].(string)) if hexErr != nil { fmt.Println("Error: " + hexErr.Error()) return } myInps[i].InputAddress = fct.ConvertFctAddressToUserStr(fct.NewAddress(decodeAddr)) myInps[i].InputSize = currInput["Amount"].(float64) } } loo := 0 loeco := 0 var outputObjects []interface{} var outputECObjects []interface{} if dat["Outputs"] != nil { outputObjects = dat["Outputs"].([]interface{}) loo = len(outputObjects) } if dat["OutECs"] != nil { outputECObjects = dat["OutECs"].([]interface{}) loeco = len(outputECObjects) } myOuts := make([]outputList, (loo + loeco)) if outputObjects != nil { if loo > 0 { currOutput := outputObjects[0].(map[string]interface{}) for i := range outputObjects { currOutput = outputObjects[i].(map[string]interface{}) decodeAddr, hexErr := hex.DecodeString(currOutput["Address"].(string)) if hexErr != nil { fmt.Println("Error: " + hexErr.Error()) return } myOuts[i].OutputAddress = fct.ConvertFctAddressToUserStr(fct.NewAddress(decodeAddr)) myOuts[i].OutputSize = currOutput["Amount"].(float64) myOuts[i].OutputType = "fct" } } } if outputECObjects != nil { if loeco > 0 { currOutput := outputECObjects[0].(map[string]interface{}) for i := range outputECObjects { currOutput = outputECObjects[i].(map[string]interface{}) decodeAddr, hexErr := hex.DecodeString(currOutput["Address"].(string)) if hexErr != nil { fmt.Println("Error: " + hexErr.Error()) return } myOuts[(i + len(outputObjects))].OutputAddress = fct.ConvertECAddressToUserStr(fct.NewAddress(decodeAddr)) myOuts[(i + len(outputObjects))].OutputSize = currOutput["Amount"].(float64) myOuts[(i + len(outputObjects))].OutputType = "ec" } } } returnTran := pseudoTransaction{ Inputs: myInps, Outputs: myOuts, } lastTry, jayErr := json.Marshal(returnTran) if jayErr != nil { w.Write([]byte(jerr.Error())) return } if jerr != nil { w.Write([]byte(jerr.Error())) return } w.Write([]byte(lastTry)) } }
// &key=<key>&name=<name or address>&amount=<amount> // If no amount is specified, a zero is returned. func getParams_(ctx *web.Context, params string, ec bool) ( trans fct.ITransaction, key string, name string, address fct.IAddress, amount int64, ok bool) { key = ctx.Params["key"] name = ctx.Params["name"] StrAmount := ctx.Params["amount"] if len(StrAmount) == 0 { StrAmount = "0" } if len(key) == 0 || len(name) == 0 { str := fmt.Sprintln("Missing Parameters: key='", key, "' name='", name, "' amount='", StrAmount, "'") reportResults(ctx, str, false) ok = false return } msg, valid := ValidateKey(key) if !valid { reportResults(ctx, msg, false) ok = false return } amount, err := strconv.ParseInt(StrAmount, 10, 64) if err != nil { str := fmt.Sprintln("Error parsing amount.\n", err) reportResults(ctx, str, false) ok = false return } // Get the transaction trans, err = getTransaction(ctx, key) if err != nil { reportResults(ctx, "Failure to locate the transaction", false) ok = false return } // Get the input/output/ec address. Which could be a name. First look and see if it is // a name. If it isn't, then look and see if it is an address. Someone could // do a weird Address as a name and fool the code, but that seems unlikely. // Could check for that some how, but there are many ways around such checks. if len(name) <= fct.ADDRESS_LENGTH { we := Wallet.GetRaw([]byte(fct.W_NAME), []byte(name)) if we != nil { address, err = we.(wallet.IWalletEntry).GetAddress() if we.(wallet.IWalletEntry).GetType() == "ec" { if !ec { reportResults(ctx, "Was Expecting a Factoid Address", false) ok = false return } } else { if ec { reportResults(ctx, "Was Expecting an Entry Credit Address", false) ok = false return } } if err != nil || address == nil { reportResults(ctx, "Should not get an error geting a address from a Wallet Entry", false) ok = false return } ok = true return } } if (!ec && !fct.ValidateFUserStr(name)) || (ec && !fct.ValidateECUserStr(name)) { reportResults(ctx, fmt.Sprintf("The address specified isn't defined or is invalid: %s", name), false) ctx.WriteHeader(httpBad) ok = false return } baddr := fct.ConvertUserStrToAddress(name) address = fct.NewAddress(baddr) ok = true return }