public static UTXO UpdateVirtualUTXO(Tx TX, UTXO utxo, bool reverse) //< get a virtual instance of a specific UTXO updated from a an unique TX { uint nSold = utxo.Sold; uint nToken = utxo.TokenOfUniqueness; if (ComputeSHA256(TX.sPKey).SequenceEqual(utxo.HashKey)) { if (!reverse) { nSold -= TX.Amount + TX.TxFee; nToken = TX.TokenOfUniqueness; } else { nSold += TX.Amount + TX.TxFee; nToken = TX.TokenOfUniqueness; } } if (TX.rHashKey.SequenceEqual(utxo.HashKey)) { if (!reverse) { nSold += TX.Amount; } else { nSold -= TX.Amount; } } return(new UTXO(utxo.HashKey, nSold, nToken)); }
public async Task GetUnconfirmedBalance() { UTXO utxo = new UTXO(); long balance = await utxo.GetUnconfirmedBalance(); Assert.IsNotNull(balance); }
public void AddForm(string stateTxn, Stage.Types.Schema schema, List <UTXO> utxos, Stage stage) { Assert.IsTrue(!string.IsNullOrEmpty(stateTxn)); payeeAddr = stage.Payee; funds = stage.Funds; Assert.IsTrue(!string.IsNullOrEmpty(payeeAddr)); stateId = stateTxn; foreach (var utxo in utxos) { if (utxo.Satoshis >= 100000) // Dont use an utxo meant for an image to submit this { continue; } submitUTXO = utxo; utxos.Remove(utxo); break; } SchemaController.BuildForm(schema, utxos.ToArray()); SchemaController.OnSubmit.AddListener(SubmitForm); }
public async Task GetListUnspentInfo() { UTXO utxo = new UTXO(); List <UnspentOM> list = await utxo.ListUnspent(2, 99999, null); Assert.IsNotNull(list); }
public override async Task <Response <List <UTXO> > > GetUTXO(List <SendingAddress> addrList) { Response <List <UTXO> > resp = new Response <List <UTXO> >(); string addresses = string.Join("|", addrList.Select(b => b.Address).ToArray()); string url = "https://chainz.cryptoid.info/grs/api.dws?q=unspent&key=632ba1ffd292&active=" + addresses; Response <JObject> apiResp = await SendApiRequestAsync(url); if (apiResp.Errors.Any()) { resp.Errors.AddRange(apiResp.Errors); return(resp); } resp.Result = new List <UTXO>(); foreach (var item in apiResp.Result["unspent_outputs"]) { UTXO u = new UTXO(); string script = item["script"].ToString(); u.AddressHash160 = script.Substring("76a914".Length, script.Length - "76a91488ac".Length); u.Address = item["addr"].ToString(); u.TxHash = item["tx_hash"].ToString(); u.Amount = (ulong)item["value"]; u.Confirmation = (int)item["confirmations"]; u.OutIndex = (uint)item["tx_ouput_n"]; resp.Result.Add(u); } return(resp); }
private static void PersistUTXO(UTXO u) { string sql = "delete from UTXO where txid='" + BMS.PurifySQL(u.TXID, 100) + "'\r\nInsert into UTXO (id,txid,ordinal,address,amount,added,spent) values (newid(), '" + BMS.PurifySQL(u.TXID, 100) + "','" + u.nOrdinal + "','" + u.Address + "','" + u.nAmount.ToString() + "',getdate(),'" + GetDouble(u.Spent) + "')"; gData.Exec(sql); }
public async Task GetTxOut() { UTXO utxo = new UTXO(); TxOutOM tx = await utxo.GetTxOut("474DF906F3A53285EC40566D0BA1AFBD4828BDD3789C9599F6EA0489C4333381", 0, false); Assert.IsNotNull(tx); }
public static string GetUTXOReport() { int nElapsed = UnixTimeStamp() - nLastUTXOReport; if (nElapsed < (60 * 60 * 1) && sCachedUTXOReport != "") { return(sCachedUTXOReport); } nLastUTXOReport = UnixTimeStamp(); string sql = "Select * from UTXO"; DataTable dt1 = gData.GetDataTable2(sql); string sData = "<utxos>"; for (int i = 0; i < dt1.Rows.Count; i++) { UTXO u = new UTXO(); u.Address = dt1.Rows[i]["Address"].ToString(); u.Found = true; u.nAmount = GetDouble(dt1.Rows[i]["Amount"]); u.Spent = Convert.ToBoolean(GetDouble(dt1.Rows[i]["Spent"])); u.TXID = dt1.Rows[i]["TXID"].ToString(); string sUTXO = SerializeUTXO(u); sData += sUTXO; } sData += "</utxos><eof></html>"; sCachedUTXOReport = sData; return(sData); }
private static UTXO GetDbUTXO(string txid, int iOrdinal) { int nElapsed = UnixTimeStamp() - nLastClean; if (nElapsed > (60 * 60 * 1)) { nLastClean = UnixTimeStamp(); string sql1 = "Delete From UTXO where Added < getdate()-1"; gData.Exec(sql1); } string sql = "Select * from UTXO where txid='" + BMS.PurifySQL(txid, 100) + "'"; DataTable dt1 = gData.GetDataTable2(sql); UTXO db1 = new UTXO(); if (dt1.Rows.Count > 0) { db1.Address = dt1.Rows[0]["Address"].ToString(); db1.TXID = txid; db1.nOrdinal = iOrdinal; db1.Found = true; db1.nAmount = GetDouble(dt1.Rows[0]["Amount"].ToString()); db1.Spent = ToBool(GetDouble(dt1.Rows[0]["Spent"].ToString())); return(db1); } return(db1); }
private async void Button_Click(object sender, RoutedEventArgs e) { utxos.Clear(); comboUtxo.Items.Clear(); System.Net.WebClient wc = new System.Net.WebClient(); listUTXO.Items.Clear(); Dictionary <string, decimal> count = new Dictionary <string, decimal>(); var str = MakeRpcUrl(this.texturl.Text, "getutxo", new MyJson.JsonNode_ValueString(textaddress.Text)); var result = await wc.DownloadStringTaskAsync(str); var json1 = MyJson.Parse(result).AsDict(); if (json1.ContainsKey("error")) { return; } var json = json1["result"].AsList(); foreach (var item in json) { UTXO txio = new UTXO(); //var use = item.GetDictItem("vinTx").AsString(); var hextxid = item.GetDictItem("txid").AsString(); txio.txid = ThinNeo.Helper.HexString2Bytes(hextxid).Reverse().ToArray(); txio.n = item.GetDictItem("n").AsInt(); var hexasset = item.GetDictItem("asset").AsString(); txio.asset = ThinNeo.Helper.HexString2Bytes(hexasset).Reverse().ToArray(); var coolasset = ThinNeo.Helper.Bytes2HexString(txio.asset); var value = decimal.Parse(item.GetDictItem("value").AsString()); txio.value = value; //if (use == "") { if (count.ContainsKey(coolasset) == false) { count[coolasset] = 0; } count[coolasset] += value; listUTXO.Items.Add(txio.txid + "[" + txio.n + "] " + value + ":" + ThinNeo.Helper.Bytes2HexString(txio.asset)); comboUtxo.Items.Add(txio); } utxos.Add(txio); //else //{ // listUTXO.Items.Add("[已花费]" + value + ":" + asset); //} } listMoney.Items.Clear(); foreach (var m in count) { listMoney.Items.Add("资产:" + m.Value + " " + m.Key); } if (comboUtxo.Items.Count > 0) { comboUtxo.SelectedIndex = 0; } }
public async Task GetTxOutSetInfo() { // Server Test UTXO utxo = new UTXO(); TxOutSetOM om = await utxo.GetTxOutSetInfo(); Assert.IsNotNull(om); }
private static string SerializeUTXO(UTXO u) { string sHash = u.TXID + "-" + u.nOrdinal.ToString(); string sData = "<utxo><hash>" + sHash + "</hash><address>" + u.Address.ToNonNullString() + "</address><amount>" + u.nAmount.ToString() + "</amount><spent>" + GetDouble(u.Spent) + "</spent></utxo><eof></html>"; return(sData); }
public static void AddDust(UTXO utxo) { using (FileStream f = new FileStream(_folderPath + "utxos", FileMode.Append)) { byte[] bytes = UTXOToBytes(utxo); f.Write(bytes, 0, bytes.Length); } CURRENT_UTXO_SIZE += 40; }
public static byte[] UTXOToBytes(UTXO utxo) { List <byte> Databuilder = new List <byte>(); Databuilder = AddBytesToList(Databuilder, utxo.HashKey); Databuilder = AddBytesToList(Databuilder, BitConverter.GetBytes(utxo.Sold)); Databuilder = AddBytesToList(Databuilder, BitConverter.GetBytes(utxo.TokenOfUniqueness)); return(ListToByteArray(Databuilder)); }
public static bool isTxValidforPending(Tx TX, UTXO sUTXO) //< this only verify tx validity with current official utxo set. ( need to verify validity for { bool dustNeeded = false; if (!VerifyTransactionDataSignature(TxToBytes(TX))) { Print("Invalid Signature"); return(false); } if (sUTXO == null) { Print("Invalid UTXO POINTER : utxo not found " + TX.sUTXOP); return(false); } if (!ComputeSHA256(TX.sPKey).SequenceEqual(sUTXO.HashKey)) { Print("Invalid UTXO POINTER"); return(false); } if (TX.rUTXOP >= 4) { UTXO rUTXO = GetOfficialUTXOAtPointer(TX.rUTXOP); if (rUTXO == null) { Print("Invalid UTXO POINTER : " + TX.rUTXOP); return(false); } if (!TX.rHashKey.SequenceEqual(rUTXO.HashKey)) { Print("Invalid UTXO POINTER" + +TX.rUTXOP); return(false); } } else { dustNeeded = true; } if (TX.TokenOfUniqueness != sUTXO.TokenOfUniqueness + 1) { Print("Invalid Token"); return(false); } //< this should be compared to a virtual UTXO if (TX.TxFee < GetFee(sUTXO, dustNeeded)) { Print("Invalid Fee"); return(false); } uint unixTimestamp = (uint)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; if (TX.LockTime < unixTimestamp) { Print("Invalid Timestamp"); return(false); } //< should Be COMPARED TO UNIX TIME! Int64 sold64 = Convert.ToInt64(sUTXO.Sold); uint sum = TX.Amount + TX.TxFee; Int64 sum64 = Convert.ToInt64(sum); if (sold64 - sum64 < 0) { return(false); } return(true); }
public static Transaction BuildTxnFromUtxo(Key spender, UTXO utxo, byte[][] msg) { // Debug.Log($"Building utxo with: {JsonConvert.SerializeObject(utxo)}"); return(BuildTxn(utxo.ToCoin(spender), spender, new[] // Outs { new KeyValuePair <Script, Money>(TxNullDataTemplate.Instance.GenerateScriptPubKey(msg), Money.Zero) })); }
public static bool OverWriteUTXOAtPointer(uint pointer, UTXO towrite) { // CAN RETURN FALSE if (pointer < 4 || pointer > CURRENT_UTXO_SIZE - 40) { return(false); } byte[] bytes = UTXOToBytes(towrite); OverWriteBytesInFile(pointer, _folderPath + "utxos", bytes); return(true); }
public override async Task <Response <List <UTXO> > > GetUTXO(List <SendingAddress> addrList) { Response <List <UTXO> > resp = new Response <List <UTXO> >(); string addresses = string.Join(";", addrList.Select(b => b.Address).ToArray()); string url = $"https://api.blockcypher.com/v1/btc/main/addrs/{addresses}?unspentOnly=true"; Response <JObject> apiResp = await SendApiRequestAsync(url); if (apiResp.Errors.Any()) { resp.Errors.AddRange(apiResp.Errors); return(resp); } resp.Result = new List <UTXO>(); if (apiResp.Result["Result"] != null) { foreach (var item in apiResp.Result["Result"]) { if ((int)item["final_n_tx"] != 0) { foreach (var tx in item["txrefs"]) { UTXO u = new UTXO() { Address = item["address"].ToString(), AddressHash160 = "", TxHash = tx["tx_hash"].ToString(), Amount = (ulong)tx["value"], Confirmation = (int)tx["confirmations"], OutIndex = (uint)tx["tx_output_n"] }; resp.Result.Add(u); } } } } else if ((int)apiResp.Result["final_n_tx"] != 0) { foreach (var tx in apiResp.Result["txrefs"]) { UTXO u = new UTXO() { Address = apiResp.Result["address"].ToString(), AddressHash160 = "", TxHash = tx["tx_hash"].ToString(), Amount = (ulong)tx["value"], Confirmation = (int)tx["confirmations"], OutIndex = (uint)tx["tx_output_n"] }; resp.Result.Add(u); } } return(resp); }
public static UTXO[] ToUTXOs(this BitIndexUTXO[] bitQueryUtxos) { var utxos = new UTXO[bitQueryUtxos.Length]; for (var i = 0; i < bitQueryUtxos.Length; i++) { utxos[i] = bitQueryUtxos[i].ToUTXO(); } return(utxos); }
// Transaction Creation Methods public static void SetUpTx(string _sprkey, string _spukey, uint sutxop, uint amount, string _rpukey, uint rutxop, uint fee, uint locktime) { //newtx sprkey: spukey: sutxop: amount: rpukey: rutxop: fee: byte[] _MyPublicKey = File.ReadAllBytes(_spukey); byte[] sUTXOPointer = BitConverter.GetBytes(sutxop); byte[] Coinamount = BitConverter.GetBytes(amount); byte[] _hashOthPublicKey = ComputeSHA256(File.ReadAllBytes(_rpukey)); byte[] rUTXOPointer = BitConverter.GetBytes(rutxop); byte[] FEE = BitConverter.GetBytes(fee); byte[] LockTime = BitConverter.GetBytes((uint)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds + locktime); if (sutxop == 0) { Print("bad pointer"); return; } UTXO utxo = GetOfficialUTXOAtPointer(sutxop); if (utxo == null) { Print("bad pointer"); return; } if (!utxo.HashKey.SequenceEqual(ComputeSHA256(_MyPublicKey))) { Print("bad pointer"); return; } uint newtou = utxo.TokenOfUniqueness + 1; byte[] TOU = BitConverter.GetBytes(newtou); bool needDust = false; if (rutxop != 0) { UTXO oUTXO = GetOfficialUTXOAtPointer(rutxop); if (oUTXO == null) { Print("bad pointer"); return; } } else { needDust = true; } if (GetFee(utxo, needDust) > fee) { Print("insuffisiant fee"); return; } if (fee + amount > utxo.Sold) { Print("insuffisiant sold"); return; } // if ( TX.TxFee < GetFee(sUTXO, dustNeeded)) { Print("Invalid Fee"); return false; } // uint sum = TX.Amount + TX.TxFee; CreateTxFile(_sprkey, _MyPublicKey, Coinamount, LockTime, sUTXOPointer, rUTXOPointer, TOU, FEE, _hashOthPublicKey); }
public static uint GetFee(UTXO utxo, bool needDust) { uint fee = 2; if (needDust) { fee += 5; } // we should aso use utxo Token of uniqueness and sold to compute the fee. also maybe currency volume return(fee); }
public static Transaction BuildSubmitTxnFromUtxo(Key spender, UTXO utxo, byte[][] msg, string payeeAddr, long funds) { // Debug.Log($"Building utxo with: {JsonConvert.SerializeObject(utxo)}"); var payeeAddress = new BitcoinPubKeyAddress(payeeAddr); return(BuildTxn(utxo.ToCoin(spender), spender, new[] // Outs { new KeyValuePair <Script, Money>(TxNullDataTemplate.Instance.GenerateScriptPubKey(msg), Money.Zero), new KeyValuePair <Script, Money>(payeeAddress.ScriptPubKey, new Money(funds, MoneyUnit.Satoshi)) })); }
// General UTXO File downgrading or upgrading or building public static void UpgradeUTXOSet(Block b) //< Apply when changing Official Blockchain Only. OverWriting UTXO depend of previous transaction. Produce dust. { foreach (Tx TX in b.Data) { UTXO utxo = GetOfficialUTXOAtPointer(TX.sUTXOP); if (utxo == null) { FatalErrorHandler(0, "no utxo found during upgrade utxo set"); return; } // FATAL ERROR utxo = UpdateVirtualUTXO(TX, utxo, false); OverWriteUTXOAtPointer(TX.sUTXOP, utxo); if (TX.rUTXOP != 0) { utxo = GetOfficialUTXOAtPointer(TX.rUTXOP); if (utxo == null) { FatalErrorHandler(0, "no utxo found during upgrade utxo set"); return; } // FATAL ERROR utxo = UpdateVirtualUTXO(TX, utxo, false); OverWriteUTXOAtPointer(TX.rUTXOP, utxo); } else { utxo = new UTXO(TX.rHashKey, TX.Amount, 0); AddDust(utxo); } } if (b.minerToken.mUTXOP != 0) { UTXO utxo = GetOfficialUTXOAtPointer(b.minerToken.mUTXOP); if (utxo == null) { FatalErrorHandler(0, "no utxo found during upgrade utxo set"); return; } // FATAL ERROR uint mSold = utxo.Sold + b.minerToken.MiningReward; uint mTOU = utxo.TokenOfUniqueness + 1; OverWriteUTXOAtPointer(b.minerToken.mUTXOP, new UTXO(b.minerToken.MinerPKEY, mSold, mTOU)); } else { UTXO utxo = new UTXO(b.minerToken.MinerPKEY, b.minerToken.MiningReward, 0); AddDust(utxo); } // overwrite currency_volume header. uint actual_volume = BitConverter.ToUInt32(GetBytesFromFile(0, 4, _folderPath + "utxos"), 0); actual_volume += GetMiningReward(b.Index); OverWriteBytesInFile(0, _folderPath + "utxos", BitConverter.GetBytes(actual_volume)); }
public static UTXO GetUTXOCache(string sTicker, string txid, int iOrdinal) { UTXO dbUTXO = GetDbUTXO(txid, iOrdinal); if (dbUTXO.Found) { return(dbUTXO); } dbUTXO = BMS.GetTxOut(sTicker, txid, iOrdinal); if (dbUTXO.Found) { PersistUTXO(dbUTXO); } return(dbUTXO); }
/// <summary> /// /// </summary> /// <param name="minConfirmations"></param> /// <param name="maxConfirmations"></param> /// <param name="addresses"></param> /// <returns></returns> public static async Task <ApiResponse> ListUnspent(int minConfirmations, int maxConfirmations = 9999, string[] addresses = null) { ApiResponse response = new ApiResponse(); try { UTXO utxo = new UTXO(); List <UnspentUtxo> unspentList = new List <UnspentUtxo>(); List <UnspentOM> result = await utxo.ListUnspent(minConfirmations, maxConfirmations, addresses); if (result != null) { foreach (var item in result) { UnspentUtxo unspent = new UnspentUtxo(); unspent.Account = item.Account; unspent.Address = item.Address; unspent.Amount = item.Amount; unspent.Confirmations = item.Confirmations; unspent.RedeemScript = item.RedeemScript; unspent.ScriptPubKey = item.ScriptPubKey; unspent.Solvable = item.Solvable; unspent.Spendable = item.Spendable; unspent.TXID = item.TXID; unspent.Vout = item.Vout; unspentList.Add(unspent); } response.Result = Newtonsoft.Json.Linq.JToken.FromObject(unspentList); } else { response.Result = null; } } catch (ApiCustomException ex) { Logger.Singleton.Error(ex.ToString()); response.Error = new ApiError(ex.ErrorCode, ex.ToString()); } catch (Exception ex) { Logger.Singleton.Error(ex.ToString()); response.Error = new ApiError(ex.HResult, ex.ToString()); } return(response); }
public static async Task <ApiResponse> ListPageUnspent(long minConfirmations, int currentPage, int pageSize, long maxConfirmations = 9999999, long minAmount = 1, long maxAmount = long.MaxValue, bool isDesc = false) { ApiResponse response = new ApiResponse(); try { UTXO utxo = new UTXO(); ListPageUnspent unspent = new ListPageUnspent(); ListPageUnspentOM result = await utxo.ListPageUnspent(minConfirmations, currentPage, pageSize, maxConfirmations, minAmount, maxAmount, isDesc); if (result != null) { foreach (var item in result.UnspentOMList) { PageUnspent output = new PageUnspent(); output.Account = item.account; output.Address = item.address; output.Amount = item.amount; output.Confirmations = item.confirmations; output.RedeemScript = item.redeemScript; output.ScriptPubKey = item.scriptPubKey; output.Solvable = item.solvable; output.Spendable = item.spendable; output.Txid = item.txid; output.Vout = item.vout; unspent.UnspentList.Add(output); } unspent.Count = result.Count; response.Result = Newtonsoft.Json.Linq.JToken.FromObject(unspent); } else { response.Result = null; } } catch (ApiCustomException ex) { Logger.Singleton.Error(ex.ToString()); response.Error = new ApiError(ex.ErrorCode, ex.ToString()); } catch (Exception ex) { Logger.Singleton.Error(ex.ToString()); response.Error = new ApiError(ex.HResult, ex.ToString()); } return(response); }
// virtualisation of UTXO 's methods when proccessing multiple transactions public static UTXO GetDownGradedVirtualUTXO(uint index, UTXO utxo) //< get a virtual instance of a specific UTXO at specific time of the official chain { for (uint i = RequestLatestBlockIndex(false); i >= index; i--) { if (i == uint.MaxValue) { break; } Block b = GetBlockAtIndex(i); if (b == null) { Print("[missing block] Downgrade UTXO aborted "); return(null); } utxo = UpdateVirtualUTXOWithFullBlock(b, utxo, true); } return(utxo); }
private void MakeTx() { List <UTXO> uList = new List <UTXO>(); foreach (var item in TxInList) { UTXO u = new UTXO(); u.TxHash = item.TxId; u.OutIndex = item.OutIndex; if (BTx.Status == BitcoinTransaction.TxStatus.Signed) { int pubKeyLength = 65; string pubKey = item.ScriptSig.Substring((item.ScriptSigLength * 2) - (pubKeyLength + 1)); u.Address = BitcoinConversions.PubKeyToBase58(pubKey); u.AddressHash160 = BitcoinConversions.ByteArrayToHex(BitcoinConversions.PubKeyToHash160(pubKey)); } else { var addr = GetAddressFromScript(item.ScriptSig); if (string.IsNullOrEmpty(addr)) { u.Address = string.Empty; u.AddressHash160 = string.Empty; } else { u.Address = addr; u.AddressHash160 = BitcoinConversions.Base58ToHash160(addr); } } uList.Add(u); } try { UInt32 lockTime = 0; RawTx = Transaction.CreateRawTx(uList, ReceiveList.ToList(), lockTime, SelectedWalletType); } catch (Exception ex) { RawTx = string.Empty; MessageBox.Show(ex.Message); } }
// Get UTXO in file public static uint GetUTXOPointer(byte[] pKey) // return a pointer from the SHA256 pKey UTXO in the UTXO Set. They are { uint byteOffset = 4; while (true) { if (byteOffset >= CURRENT_UTXO_SIZE) { return(0); } UTXO utxo = BytesToUTXO(GetBytesFromFile(byteOffset, 40, _folderPath + "utxos")); if (utxo.HashKey.SequenceEqual(pKey)) { return(byteOffset); } byteOffset += 40; } }
public static List <UTXO> DeserU(JToken j) { List <UTXO> uList = new List <UTXO>(); foreach (var item in j["unspent"]) { UTXO u = new UTXO(); u.Address = j["address"].ToString(); string script = item["script"].ToString(); u.AddressHash160 = script.Substring(6, script.Length - 10); u.TxHash = item["tx"].ToString(); u.OutIndex = (UInt32)item["n"]; u.Confirmation = (int)item["confirmations"]; u.Amount = (int)((decimal)item["amount"] * 100000000); uList.Add(u); } return(uList); }