Example #1
0
        public async Task <object> Find(string data)
        {
            data = data.Trim();
            var b58 = NoException(() => WhatIsBase58.GetFromBase58Data(data));

            if (b58 != null)
            {
                if (b58 is WhatIsAddress)
                {
                    var address = (WhatIsAddress)b58;
                    TryFetchRedeemOrPubKey(address);
                }
                return(b58);
            }

            if (data.Length == 0x40)
            {
                try
                {
                    return(await Controller.JsonTransaction(uint256.Parse(data), false));
                }
                catch
                {
                }
            }
            var b = NoException(() => Controller.JsonBlock(BlockFeature.Parse(data), true, false));

            if (b != null)
            {
                return(b);
            }

            if (data.Length == 0x28) //Hash of pubkey or script
            {
                TxDestination dest    = new KeyId(data);
                var           address = new WhatIsAddress(dest.GetAddress(Network));
                if (TryFetchRedeemOrPubKey(address))
                {
                    return(address);
                }

                dest    = new ScriptId(data);
                address = new WhatIsAddress(dest.GetAddress(Network));
                if (TryFetchRedeemOrPubKey(address))
                {
                    return(address);
                }
            }


            var script = NoException(() => GetScriptFromBytes(data));

            if (script != null)
            {
                return(new WhatIsScript(script, Network));
            }
            script = NoException(() => GetScriptFromText(data));
            if (script != null)
            {
                return(new WhatIsScript(script, Network));
            }

            var sig = NoException(() => new TransactionSignature(Encoders.Hex.DecodeData(data)));

            if (sig != null)
            {
                return(new WhatIsTransactionSignature(sig));
            }

            var pubkeyBytes = NoException(() => Encoders.Hex.DecodeData(data));

            if (pubkeyBytes != null && PubKey.Check(pubkeyBytes, true))
            {
                var pubKey = NoException(() => new PubKey(data));
                if (pubKey != null)
                {
                    return(new WhatIsPublicKey(pubKey, Network));
                }
            }

            if (data.Length == 80 * 2)
            {
                var blockHeader = NoException(() =>
                {
                    var h = new BlockHeader();
                    h.ReadWrite(Encoders.Hex.DecodeData(data));
                    return(h);
                });
                if (blockHeader != null)
                {
                    return(new WhatIsBlockHeader(blockHeader));
                }
            }
            return(null);
        }
Example #2
0
 public DoScriptEvent(ScriptId scriptId) => ScriptId = scriptId;
Example #3
0
 public AssetId(ScriptId scriptId)
 {
     _Bytes = scriptId.ToBytes(true);
 }
 // Posts the current time information to the given script id
 // targetScriptId will be AllScripts for the broadcast
 void sendElapsed(ScriptId targetScriptId)
 {
     PostScriptEvent(targetScriptId, elapsedCommand, resetTime);
 }
Example #5
0
 /// <summary>
 /// Constructor.
 /// Set specified wait milliseconds.
 /// </summary>
 /// <param name="waitMillis">The required whole number of milliseconds for wait.</param>
 /// <param name="playScript">TRUE means play a startup script.</param>
 /// <param name="scriptId">The script id of the script to play.</param>
 /// <param name="repeatCount">The number of repeats to play the script. 0 means play the script forever.</param>
 /// <param name="fadeSpeed">Fade speed, between 0 and 255.</param>
 /// <param name="adjustSpeed">Playback speed, between -128 and 127. 0 resets the playback spped to the default.</param>
 public SetStartupParametersCommand(int waitMillis, bool playScript, ScriptId scriptId, byte repeatCount, byte fadeSpeed, sbyte adjustSpeed)
     : base(waitMillis, CommandHeader.Set_Startup_Parameters, playScript ? (byte)0x01 : (byte)0x00, (byte)scriptId, repeatCount, fadeSpeed, adjustSpeed > -1 ? (byte)adjustSpeed : (byte)(((adjustSpeed << 1) >> 1) | 0x80))
 {
 }
Example #6
0
        public void base58_keys_valid_gen()
        {
            var tests = TestCase.read_json("data/base58_keys_valid.json");

            tests = tests.Concat(TestCase.read_json("data/base58_keys_valid2.json")).ToArray();
            Network network = null;

            foreach (var test in tests)
            {
                string strTest = test.ToString();
                if (test.Count < 3)                // Allow for extra stuff (useful for comments)
                {
                    Assert.False(true, "Bad test: " + strTest);
                    continue;
                }
                string  exp_base58string = (string)test[0];
                byte[]  exp_payload      = TestUtils.ParseHex((string)test[1]);
                dynamic metadata         = test.GetDynamic(2);
                bool    isPrivkey        = (bool)metadata.isPrivkey;
                bool    isTestnet        = (bool)metadata.isTestnet;

                if (isTestnet)
                {
                    network = Network.TestNet;
                }
                else
                {
                    network = Network.Main;
                }
                if (isPrivkey)
                {
                    bool          isCompressed = metadata.isCompressed;
                    Key           key          = new Key(exp_payload, fCompressedIn: isCompressed);
                    BitcoinSecret secret       = network.CreateBitcoinSecret(key);
                    Assert.True(secret.ToString() == exp_base58string, "result mismatch: " + strTest);
                }
                else
                {
                    string        exp_addrType = (string)metadata.addrType;
                    TxDestination dest;
                    if (exp_addrType == "pubkey")
                    {
                        dest = new KeyId(new uint160(exp_payload));
                    }
                    else if (exp_addrType == "script")
                    {
                        dest = new ScriptId(new uint160(exp_payload));
                    }
                    else if (exp_addrType == "p2wpkh")
                    {
                        dest = new WitKeyId(new uint160(exp_payload));
                    }
                    else if (exp_addrType == "p2wsh")
                    {
                        dest = new WitScriptId(exp_payload);
                    }
                    else if (exp_addrType == "none")
                    {
                        continue;
                    }
                    else
                    {
                        Assert.True(false, "Bad addrtype: " + strTest);
                        continue;
                    }
                    try
                    {
                        BitcoinAddress addrOut = dest.GetAddress(network);
                        Assert.True(addrOut.ToString() == exp_base58string, "mismatch: " + strTest);
                        Assert.True(addrOut.ScriptPubKey == dest.ScriptPubKey);
                        Assert.True(dest.ScriptPubKey.GetDestination() == dest);
                    }
                    catch (ArgumentException)
                    {
                        Assert.True(dest.GetType() == typeof(TxDestination));
                    }
                }
            }
        }
Example #7
0
 public ScriptHashScanner(ScriptId scriptId)
 {
     _ScriptId = scriptId;
 }
Example #8
0
 public AddressInvoiceData SetHash(ScriptId scriptId, string cryptoCode)
 {
     Address = scriptId + "#" + cryptoCode;
     return(this);
 }
Example #9
0
 /// <summary>
 /// Constructor.
 /// No specified wait milliseconds.
 /// </summary>
 /// <param name="scriptId">The script id of the script to play forever.</param>
 public PlayLightScriptCommand(ScriptId scriptId)
     : this(0, scriptId, 0)
 {
 }
Example #10
0
 public ScriptHashScanner(ScriptId scriptId)
 {
     _ScriptId = scriptId;
 }
Example #11
0
        public bool MatchScriptHash(TxOut output)
        {
            ScriptId id = template.ExtractScriptPubKeyParameters(output.ScriptPubKey);

            return(id == ScriptId);
        }
Example #12
0
    public static string ReplaceScriptIdsInLine(string line, List <ScriptId> oldIds, List <ScriptId> newIds,
                                                HashSet <string> replacedScriptNames)
    {
        //	if (oldIds.Count != newIds.Count)
        //		throw new ArgumentException ("Number of old and new ids must be the same");

        // find guid and fileId inside a line

        string guid   = "";
        string fileId = "";

        if (!GetGuidAndFileIdFromLine(line, ref guid, ref fileId))
        {
            return(line);
        }

        // check if this guid and fileId match any of old scripts
        ScriptId matchingOldScriptId = oldIds.Find(id => id.fileId == fileId && id.guid == guid);

        if (matchingOldScriptId != null)
        {
            // found matching script

            // replace it with new script
            // replace both file id and guid

            // find new script
            //	var matchingNewScriptIds = new List<ScriptId>() { newIds[ oldIds.IndexOf(matchingOldScriptId) ] } ;
            var matchingNewScriptIds = newIds.FindAll(id => id.TypeName == matchingOldScriptId.TypeName);

            if (matchingNewScriptIds.Count > 1)
            {
                Debug.LogError("Found " + matchingNewScriptIds.Count + " matching scripts (new) for " + matchingOldScriptId.TypeName);
            }
            else if (0 == matchingNewScriptIds.Count)
            {
                // no matches
                Debug.LogWarning("No match for " + matchingOldScriptId.TypeName);
            }
            else
            {
                // found exactly 1 new script which matches
                // replace ids

                var newScriptId = matchingNewScriptIds [0];

                line = line.Replace("guid: " + guid, "guid: " + newScriptId.guid);

                line = line.Replace("fileID: " + fileId, "fileID: " + newScriptId.fileId);

                //	replacedScriptNames.Add (newScriptId.type.ToString ());
            }
        }
        else
        {
            //	string path = AssetDatabase.GUIDToAssetPath (guid);
            //	Debug.LogWarning ("no match for old script - guid " + guid + ", fileID " + fileId + ", path " + path);

            if (oldIds.Exists(id => id.guid == guid))
            {
                Debug.LogError("Found a script which matches guid " + guid + ", but has unknown fileID " + fileId);
            }
        }

        return(line);
    }
Example #13
0
        private static ColoredTransaction FetchColorsWithAncestorsSolved(uint256 txId, Transaction tx, IColoredTransactionRepository repo)
        {
            ColoredTransaction colored = new ColoredTransaction();

            Queue <ColoredEntry> previousAssetQueue = new Queue <ColoredEntry>();

            for (int i = 0; i < tx.Inputs.Count; i++)
            {
                var txin        = tx.Inputs[i];
                var prevColored = repo.Get(txin.PrevOut.Hash);
                if (prevColored == null)
                {
                    continue;
                }
                var prevAsset = prevColored.GetColoredEntry(txin.PrevOut.N);
                if (prevAsset != null)
                {
                    var input = new ColoredEntry()
                    {
                        Index = i,
                        Asset = prevAsset.Asset
                    };
                    previousAssetQueue.Enqueue(input);
                    colored.Inputs.Add(input);
                }
            }

            int markerPos = 0;
            var marker    = ColorMarker.Get(tx, out markerPos);

            if (marker == null)
            {
                repo.Put(txId, colored);
                return(colored);
            }
            colored.Marker = marker;
            if (!marker.HasValidQuantitiesCount(tx))
            {
                repo.Put(txId, colored);
                return(colored);
            }

            ScriptId issuedAsset = null;

            for (int i = 0; i < markerPos; i++)
            {
                var entry = new ColoredEntry();
                entry.Index          = i;
                entry.Asset.Quantity = i >= marker.Quantities.Length ? 0 : marker.Quantities[i];
                if (entry.Asset.Quantity == 0)
                {
                    continue;
                }

                if (issuedAsset == null)
                {
                    var txIn = tx.Inputs.FirstOrDefault();
                    if (txIn == null)
                    {
                        continue;
                    }
                    var prev = repo.Transactions.Get(txIn.PrevOut.Hash);
                    if (prev == null)
                    {
                        throw new TransactionNotFoundException("This open asset transaction is issuing assets, but it needs a parent transaction in the TransactionRepository to know the address of the issued asset (missing : " + txIn.PrevOut.Hash + ")", txIn.PrevOut.Hash);
                    }
                    issuedAsset = prev.Outputs[(int)txIn.PrevOut.N].ScriptPubKey.ID;
                }
                entry.Asset.Id = issuedAsset;
                colored.Issuances.Add(entry);
            }

            ulong used = 0;

            for (int i = markerPos + 1; i < tx.Outputs.Count; i++)
            {
                var entry = new ColoredEntry();
                entry.Index = i;
                //If there are less items in the  asset quantity list  than the number of colorable outputs (all the outputs except the marker output), the outputs in excess receive an asset quantity of zero.
                entry.Asset.Quantity = (i - 1) >= marker.Quantities.Length ? 0 : marker.Quantities[i - 1];
                if (entry.Asset.Quantity == 0)
                {
                    continue;
                }

                //If there are less asset units in the input sequence than in the output sequence, the transaction is considered invalid and all outputs are uncolored.
                if (previousAssetQueue.Count == 0)
                {
                    colored.Transfers.Clear();
                    colored.Issuances.Clear();
                    repo.Put(txId, colored);
                    return(colored);
                }
                entry.Asset.Id = previousAssetQueue.Peek().Asset.Id;
                var remaining = entry.Asset.Quantity;
                while (remaining != 0)
                {
                    if (previousAssetQueue.Count == 0 || previousAssetQueue.Peek().Asset.Id != entry.Asset.Id)
                    {
                        colored.Transfers.Clear();
                        colored.Issuances.Clear();
                        repo.Put(txId, colored);
                        return(colored);
                    }
                    var assertPart = Math.Min(previousAssetQueue.Peek().Asset.Quantity - used, remaining);
                    remaining = remaining - assertPart;
                    used     += assertPart;
                    if (used == previousAssetQueue.Peek().Asset.Quantity)
                    {
                        previousAssetQueue.Dequeue();
                        used = 0;
                    }
                }
                colored.Transfers.Add(entry);
            }
            repo.Put(txId, colored);
            return(colored);
        }
 public PayToScriptHashSigParameters ExtractScriptSigParameters(Network network, Script scriptSig, ScriptId expectedScriptId)
 {
     if (expectedScriptId == null)
     {
         return(ExtractScriptSigParameters(network, scriptSig, null as Script));
     }
     return(ExtractScriptSigParameters(network, scriptSig, expectedScriptId.ScriptPubKey));
 }
Example #15
0
 public DumpScriptEvent(ScriptId scriptId) => ScriptId = scriptId;
Example #16
0
 /// <summary>
 /// Constructor.
 /// No specified wait milliseconds.
 /// </summary>
 /// <param name="scriptId">The script id of the script to play.</param>
 /// <param name="repeatCount">The number of repeats to play the script. 0 means play the script forever.</param>
 public PlayLightScriptCommand(ScriptId scriptId, byte repeatCount)
     : this(0, scriptId, repeatCount)
 {
 }
Example #17
0
 public static AssetId ToAssetId(this ScriptId id)
 {
     return(new AssetId(id));
 }
Example #18
0
 /// <summary>
 /// Constructor.
 /// Set specified wait milliseconds.
 /// </summary>
 /// <param name="waitMillis">The required whole number of milliseconds for wait.</param>
 /// <param name="scriptId">The script id of the script to play.</param>
 /// <param name="repeatCount">The number of repeats to play the script. 0 means play the script forever.</param>
 public PlayLightScriptCommand(int waitMillis, ScriptId scriptId, byte repeatCount)
     : base(waitMillis, CommandHeader.Play_Light_Script, (byte)scriptId, repeatCount, 0x00)
 {
 }
Example #19
0
		public void base58_keys_valid_gen()
		{
			var tests = TestCase.read_json("data/base58_keys_valid.json");
			tests = tests.Concat(TestCase.read_json("data/base58_keys_valid2.json")).ToArray();
			Network network = null;

			foreach(var test in tests)
			{
				string strTest = test.ToString();
				if(test.Count < 3) // Allow for extra stuff (useful for comments)
				{
					Assert.False(true, "Bad test: " + strTest);
					continue;
				}
				string exp_base58string = (string)test[0];
				byte[] exp_payload = TestUtils.ParseHex((string)test[1]);
				dynamic metadata = test.GetDynamic(2);
				bool isPrivkey = (bool)metadata.isPrivkey;
				bool isTestnet = (bool)metadata.isTestnet;

				if(isTestnet)
					network = Network.TestNet;
				else
					network = Network.Main;
				if(isPrivkey)
				{
					bool isCompressed = metadata.isCompressed;
					Key key = new Key(exp_payload, fCompressedIn: isCompressed);
					BitcoinSecret secret = network.CreateBitcoinSecret(key);
					Assert.True(secret.ToString() == exp_base58string, "result mismatch: " + strTest);
				}
				else
				{
					string exp_addrType = (string)metadata.addrType;
					TxDestination dest;
					if(exp_addrType == "pubkey")
					{
						dest = new KeyId(new uint160(exp_payload));
					}
					else if(exp_addrType == "script")
					{
						dest = new ScriptId(new uint160(exp_payload));
					}
					else if(exp_addrType == "p2wpkh")
					{
						network = network == Network.TestNet ? Network.SegNet : network;
						dest = new WitKeyId(new uint160(exp_payload));
					}
					else if(exp_addrType == "p2wsh")
					{
						network = network == Network.TestNet ? Network.SegNet : network;
						dest = new WitScriptId(exp_payload);
					}
					else if(exp_addrType == "none")
					{
						continue;
					}
					else
					{
						Assert.True(false, "Bad addrtype: " + strTest);
						continue;
					}
					try
					{
						BitcoinAddress addrOut = dest.GetAddress(network);
						Assert.True(addrOut.ToString() == exp_base58string, "mismatch: " + strTest);
						Assert.True(addrOut.ScriptPubKey == dest.ScriptPubKey);
						Assert.True(dest.ScriptPubKey.GetDestination() == dest);
					}
					catch(ArgumentException)
					{
						Assert.True(dest.GetType() == typeof(TxDestination));
					}
				}
			}
		}
Example #20
0
 /// <summary>
 /// Constructor.
 /// No specified wait milliseconds.
 /// </summary>
 /// <param name="playScript">TRUE means play a startup script.</param>
 /// <param name="scriptId">The script id of the script to play.</param>
 /// <param name="repeatCount">The number of repeats to play the script. 0 means play the script forever.</param>
 /// <param name="fadeSpeed">Fade speed, between 0 and 255.</param>
 /// <param name="adjustSpeed">Playback speed, between -128 and 127. 0 resets the playback spped to the default.</param>
 public SetStartupParametersCommand(bool playScript, ScriptId scriptId, byte repeatCount, byte fadeSpeed, sbyte adjustSpeed)
     : this(20, playScript, scriptId, repeatCount, fadeSpeed, adjustSpeed)
 {
 }
Example #21
0
		public AssetId(ScriptId scriptId)
		{
			if (scriptId == null) throw new ArgumentNullException("scriptId");
			_Bytes = scriptId.ToBytes(true);
		}
Example #22
0
        /// <summary>
        /// Try to interpret the given string in a few ways in order to detect what object it's supposed to represent.
        /// </summary>
        /// <returns>The object represented by the input string. This may be a Bitcoin address, a script, a signature, a public key, etc.</returns>
        public async Task <object> Find(string data)
        {
            data = data.Trim();


            // Is it a Bitcoin address?
            var b58 = NoException(() => WhatIsBase58.GetFromBitcoinString(data));

            if (b58 != null)
            {
                if (b58 is WhatIsAddress address)
                {
                    await TryFetchRedeemOrPubKey(address);  // Shouldn't the return value here be checked?
                }

                return(b58);
            }


            // Is it a transaction ID?
            if (data.Length == 0x40)
            {
                try
                {
                    return(await Controller.JsonTransaction(uint256.Parse(data), false));
                }
                catch
                {
                    // Well, apparently it's not a transaction ID.
                }
            }


            // Is it a block feature?
            var b = NoException(() => Controller.JsonBlock(BlockFeature.Parse(data), true, false));

            if (b != null)
            {
                return(b);
            }


            // Is it the hash of a public key (modeled as KeyId in NBitcoin), or is it the hash of a script ID?
            if (data.Length == 0x28) // Hash of pubkey or script
            {
                TxDestination dest = new KeyId(data);

                var address = new WhatIsAddress(dest.GetAddress(Network));

                if (await TryFetchRedeemOrPubKey(address))
                {
                    return(address);
                }

                dest    = new ScriptId(data);
                address = new WhatIsAddress(dest.GetAddress(Network));

                if (await TryFetchRedeemOrPubKey(address))
                {
                    return(address);
                }
            }


            // Is it a script?
            var script = NoException(() => GetScriptFromBytes(data));

            if (script != null)
            {
                return(new WhatIsScript(script, Network));
            }

            script = NoException(() => GetScriptFromText(data));

            if (script != null)
            {
                return(new WhatIsScript(script, Network));
            }


            // Is it a transaction signature?
            var sig = NoException(() => new TransactionSignature(Encoders.Hex.DecodeData(data)));

            if (sig != null)
            {
                return(new WhatIsTransactionSignature(sig));
            }


            // Is it a hexstring representing the bytes of a public key?
            var pubkeyBytes = NoException(() => Encoders.Hex.DecodeData(data));

            if (pubkeyBytes != null && PubKey.Check(pubkeyBytes, true))
            {
                var pubKey = NoException(() => new PubKey(data));

                if (pubKey != null)
                {
                    return(new WhatIsPublicKey(pubKey, Network));
                }
            }


            // Is it a blockheader?
            if (data.Length == 80 * 2)
            {
                var blockHeader = NoException(() =>
                {
                    var h = ConsensusFactory.CreateBlockHeader();
                    h.ReadWrite(Encoders.Hex.DecodeData(data), ConsensusFactory);
                    return(h);
                });

                if (blockHeader != null)
                {
                    return(new WhatIsBlockHeader(blockHeader));
                }
            }


            // No idea what this is.
            return(null);
        }