Exemple #1
0
        // hash256(hsah + index)
        public string utoxHashCode()
        {
            string strUtox = this.strTxHash + this.index;
            string strHash = Cryptor.SHA256(strUtox, strUtox.Length);

            return(strHash);
        }
Exemple #2
0
        private void OP_HASH160()
        {
            string strTemp = this.staData.Pop();

            strTemp = Cryptor.SHA256(strTemp, strTemp.Length);
            this.staData.Push(strTemp);
        }
Exemple #3
0
        public Block CreatBlock(string strNounce, string sBaseCoinScript)
        {
            try
            {
                Block block = new Block();

                if (!Cryptor.Verify24Puzzel(this.mLastBlock.Header.Puzzle, strNounce))
                {
                    return(block);
                }

                // mutex todo 181215
                Transaction basecoinTrans = this.CreatCoinBaseTX(sBaseCoinScript);
                this.AddTx2hsPool(basecoinTrans);
                this.HashsetPool2list();

                block.listTransactions = this.GetlstPoolTx();
                block.SetTransInfo();
                block.SetBlockHeader(this.mLastBlock.Hash, this.mLastBlock.Header.Height);

                block.SetNonce(strNounce);
                block.SetBlockHash();

                string jsonblock = JsonHelper.Serializer <Block>(block);
                LogHelper.WriteInfoLog(jsonblock);
                return(block);
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog(ex.Message);
                Block block = new Block();
                return(block);
            }
        }
Exemple #4
0
        public string CalMerkleRoot(List <string> lstHash)
        {
            //step2: 相邻两个hash块串联,然后做hash运算,Node1((i + 1) / 2) = hash(Node0i + Node0(i + 1)),
            //       i = 1,3,5,7; 对于i = 9, Node1((i + 1) / 2) = hash(Node0i)
            //step3: 重复step2
            //step4: 重复step2
            //step5: 重复step2,生成Merkle Tree Root
            List <string> lstTemp = new List <string>();

            int index = 0;

            while (index < lstHash.Count())
            {
                // left
                String left = lstHash[index];
                index++;
                // right
                String right = left;
                if (index != lstHash.Count())
                {
                    right = lstHash[index];
                }
                // sha2 hex value
                string LeftAndRight = left + right;
                String sha2HexValue = Cryptor.SHA256(LeftAndRight, LeftAndRight.Length);
                lstTemp.Add(sha2HexValue);
                index++;
            }
            if (lstTemp.Count > 1)
            {
                CalMerkleRoot(lstTemp);
            }

            return(lstTemp[0]);
        }
Exemple #5
0
        /// <summary>
        /// input.hash + index + (该笔交易的所有output的value+pub)
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public string getRawDataToSign(int index)
        {
            // ith input and all outputs
            // sigdata = input.hash + index + (该笔交易的所有output的value+pub)
            string strSigData;

            if (index > listInputs.Count())
            {
                return(null);
            }
            Input inEnty = listInputs[index];

            strSigData = inEnty.PreTxHash + inEnty.OutputIndex;

            string strAllOutput = string.Empty;

            foreach (Output opEnty in listOutputs)
            {
                strAllOutput += opEnty.value + opEnty.scriptPubKey;
            }
            strSigData += strAllOutput;

            string sigDataHash = Cryptor.SHA256(strSigData, strSigData.Length);

            return(sigDataHash);
        }
Exemple #6
0
        public string CalTransHash()
        {
            string strTransction = getRawTx();
            string strTransHash  = Cryptor.SHA256(strTransction, strTransction.Length);

            return(strTransHash);
        }
Exemple #7
0
        public void signTrans(string strmyPriKeyPath, string strmyPubkeyValue, int InputIndex)
        {
            string strRawdata = this.getRawDataToSign(InputIndex);

            listInputs[InputIndex].ScriptSig.Signature = Cryptor.rsaPriSign(strRawdata, strmyPriKeyPath);
            listInputs[InputIndex].ScriptSig.PubKey    = strmyPubkeyValue;
        }
Exemple #8
0
        public MultiSignViewModel MultiSignUTXOPool2VM(bool bCommited)
        {
            LogHelper.WriteMethodLog(true);
            Dictionary <UTXO, Output> dicMsUTXOPool = new Dictionary <UTXO, Output>();

            if (bCommited)
            {
                dicMsUTXOPool = this.dicComitMsUTXOPool;
            }
            else
            {
                dicMsUTXOPool = this.dicUnComitMsUTXOPool;
            }

            MultiSignViewModel msVM = new MultiSignViewModel();

            foreach (var item in dicMsUTXOPool)
            {
                MultiSignModel msSM = new MultiSignModel();

                msSM.TxHash          = item.Key.getTxHash();
                msSM.OutputIndex     = (int)item.Key.getIndex();
                msSM.Value           = item.Value.value;
                msSM.OutScriptPKHash = item.Value.getPKHashFromScript();
                msSM.ID           = Cryptor.SHA256(msSM.OutScriptPKHash, msSM.OutScriptPKHash.Length).Substring(0, 8);
                msSM.BIsAdd2PriTx = false;
                msVM.AddItem(msSM);
            }
            LogHelper.WriteMethodLog(false);
            return(msVM);
        }
Exemple #9
0
        public string CalBlockHash()
        {
            string strHeader = this.Header.HeaderToStr();
            // 计算两遍sha
            string strhash = Cryptor.SHA256(strHeader, strHeader.Length);

            strhash = Cryptor.SHA256(strhash, strhash.Length);
            return(strhash);
        }
Exemple #10
0
        public string pubkey2Hash(string pubKeyPath)
        {
            LogHelper.WriteMethodLog(true);
            string strPubKeyValue = FileIOHelper.ReadFromText(pubKeyPath);
            string strKeyHash     = Cryptor.SHA256(strPubKeyValue, strPubKeyValue.Length);

            LogHelper.WriteMethodLog(false);
            return(strKeyHash);
        }
Exemple #11
0
        public void MultiSignTrans(string strmyPriKeyPath, string strmyPubkeyValue, int InputIndex)
        {
            string    strRawdata    = this.getRawDataToSign(InputIndex);
            scriptSig tempScriptSig = new scriptSig();

            tempScriptSig.Signature = Cryptor.rsaPriSign(strRawdata, strmyPriKeyPath);
            tempScriptSig.PubKey    = strmyPubkeyValue;
            listInputs[InputIndex].addMutiSignTolst(tempScriptSig);
        }
Exemple #12
0
        private string OP_CHECKSIG()
        {
            string strPubkey = this.staData.Pop();
            string strSign   = this.staData.Pop();

            string strRet = Cryptor.rsaPubDecrySign(strSign, strPubkey, false);

            return(strRet);
        }
Exemple #13
0
 public void signTrans(string strmyPriKeyPath, string strmyPubkeyValue)
 {
     for (int i = 0; i < this.listInputs.Count; i++)
     {
         string strRawdata = this.getRawDataToSign(i);
         listInputs[i].ScriptSig.Signature = Cryptor.rsaPriSign(strRawdata, strmyPriKeyPath);
         listInputs[i].ScriptSig.PubKey    = strmyPubkeyValue;
     }
 }
Exemple #14
0
        public string pubkey2Script(string pubKeyPath)
        {
            LogHelper.WriteMethodLog(true);
            string strPubKeyValue = FileIOHelper.ReadFromText(pubKeyPath);
            string strKeyHash     = Cryptor.SHA256(strPubKeyValue, strPubKeyValue.Length);
            string strPubScript   = string.Format("OP_DUP OP_HASH160 {0} OP_EQUALVERIFY OP_CHECKSIG", strKeyHash);

            LogHelper.WriteMethodLog(false);
            return(strPubScript);
        }
Exemple #15
0
 /// <summary>
 /// 计算当前交易的hash
 /// </summary>
 public void SetTransHash()
 {
     try
     {
         string strTransction = getRawTx();
         this.TxHash = Cryptor.SHA256(strTransction, strTransction.Length);
     }
     catch (Exception ex)
     {
         LogHelper.WriteErrorLog(ex.Message);
     }
 }
Exemple #16
0
        public void signTrans(string strmyPriKeyPath, string strmyPubkeyValue, int InputIndex)
        {
            string    strRawdata    = this.getRawDataToSign(InputIndex);
            scriptSig tempScriptSig = new scriptSig();

            tempScriptSig.Signature = Cryptor.rsaPriSign(strRawdata, strmyPriKeyPath);
            tempScriptSig.PubKey    = strmyPubkeyValue;

            // modified by fdp 190110
            listInputs[InputIndex].addSignature(tempScriptSig);
            //listInputs[InputIndex].ScriptSig.Signature = Cryptor.rsaPriSign(strRawdata, strmyPriKeyPath);
            //listInputs[InputIndex].ScriptSig.PubKey = strmyPubkeyValue;
        }
Exemple #17
0
        private void CreatPuzzle()
        {
            this.Puzzle = new int[4];
            Random rd = new Random();

            bool bCreatPuzzle = false;

            while (!bCreatPuzzle)
            {
                for (int i = 0; i < 4; i++)
                {
                    this.Puzzle[i] = rd.Next(1, 11);
                }
                bCreatPuzzle = Cryptor.Calc24(this.Puzzle);
            }
        }
Exemple #18
0
        private bool OP_CHECKMULTISIG(ref string strDecResult)
        {
            strDecResult = string.Empty;
            List <string> lstPKHash = new List <string>();

            for (int i = 0; i < this.M; i++)
            {
                lstPKHash.Add(this.staData.Pop());
            }

            List <string> lstDecryptRes = new List <string>();

            for (int j = 0; j < this.N; j++)
            {
                this.OP_DUP();
                string strTemp = this.staData.Pop();
                strTemp = Cryptor.SHA256(strTemp, strTemp.Length);
                if (lstPKHash.Contains(strTemp))
                {
                    string strDecRes = OP_CHECKSIG();
                    if (string.IsNullOrEmpty(strDecRes))
                    {
                        LogHelper.WriteErrorLog("check signature fail");
                        return(false);
                    }
                    else
                    {
                        lstDecryptRes.Add(strDecRes);
                    }
                }
            }

            string strResult1 = lstDecryptRes[0];

            foreach (var item in lstDecryptRes)
            {
                if (!string.Equals(item, strResult1))
                {
                    LogHelper.WriteErrorLog(string.Format("Result not equal, ret[0]:{0}, otherRet:{1}", strResult1, item));
                    return(false);
                }
            }

            strDecResult = strResult1;
            return(true);
        }
Exemple #19
0
        public Transaction CreatCoinBaseTX(string strAddress)
        {
            Transaction basecoinTrans   = new Transaction();
            string      basecoinPrehash = "0000000000000000000000000000000000000000000000000000000000000000";
            int         basecoinIndex   = -1;
            Input       basecoinInput   = new Input(basecoinPrehash, basecoinIndex);
            scriptSig   bassecoinSS     = new scriptSig();
            string      nowTime         = DateTime.Now.ToString("yyyyMMddHHmmssfff");

            bassecoinSS.Signature = Cryptor.SHA256(nowTime, nowTime.Length);
            bassecoinSS.PubKey    = Cryptor.SHA256(bassecoinSS.Signature, bassecoinSS.Signature.Length);
            basecoinInput.addSignature(bassecoinSS);
            basecoinTrans.addInput(basecoinInput);

            basecoinTrans.addOutput(24, strAddress);
            basecoinTrans.FinalSetTrans();
            return(basecoinTrans);
            //this.poolTx.Add(RewardTrans);
        }
Exemple #20
0
        public Block CreatBlock(string strNounce, string sBaseCoinScript)
        {
            try
            {
                LogHelper.WriteMethodLog(true);
                Block block = new Block();

                if (!Cryptor.Verify24Puzzel(this.mLastBlock.Header.Puzzle, strNounce))
                {
                    return(block);
                }

                // mutex todo 181215
                Transaction basecoinTrans = this.CreatCoinBaseTX(sBaseCoinScript);
                this.AddTx2hsPool(basecoinTrans);
                //this.HashsetPool2list();

                block.listTransactions = this.GetlstPoolTx();
                this.ClearTxPool();
                block.SetTransInfo();
                block.SetBlockHeader(this.mLastBlock.Hash, this.mLastBlock.Header.Height);

                block.SetNonce(strNounce);
                //add by fdp 190114 set hash all 0 temporary for computing block size,
                block.Hash = ConstHelper.BC_BaseCoinInputTxHash;
                string jsonBlock = JsonHelper.Serializer <Block>(block);
                block.SetBlockSize(jsonBlock.Length);

                block.SetBlockHash();

                string jsonblock = JsonHelper.Serializer <Block>(block);
                LogHelper.WriteInfoLog(jsonblock);
                return(block);
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog(ex.Message);
                Block block = new Block();
                return(block);
            }
        }
Exemple #21
0
        public Transaction CreatTransaction(string strPreHash, uint iIndex, double dValue,
                                            string strPaytoPKHash, string myPriKeyPath, string myPubkeyPath)
        {
            LogHelper.WriteMethodLog(true);

            string strPubKeyValuem = FileIOHelper.ReadFromText(myPubkeyPath);
            string strKeyHash      = Cryptor.SHA256(strPubKeyValuem, strPubKeyValuem.Length);
            string myPubScript     = string.Format("OP_DUP OP_HASH160 {0} OP_EQUALVERIFY OP_CHECKSIG", strKeyHash);


            UTXO utxo = new UTXO(strPreHash, iIndex);

            if (!this.CommitedUtxoPool.contains(utxo))
            {
                LogHelper.WriteErrorLog("not in utxo");
                return(null);
            }

            Transaction spendTrans = new Transaction();

            spendTrans.addInput(strPreHash, (int)iIndex);
            spendTrans.addOutput(dValue, strPaytoPKHash);

            Output preOutput = this.CommitedUtxoPool.getTxOutput(utxo);

            if (dValue < preOutput.value)
            {
                Output ctOutput = new Output();
                ctOutput.value        = preOutput.value - dValue;
                ctOutput.scriptPubKey = myPubScript;
                spendTrans.addOutput(ctOutput);
            }
            spendTrans.signTrans(myPriKeyPath, strPubKeyValuem);
            spendTrans.FinalSetTrans();

            LogHelper.WriteInfoLog("CreatTransaction: " + spendTrans.TxHash);
            return(spendTrans);
        }
Exemple #22
0
        public string   GernerateKeypairs()
        {
            LogHelper.WriteMethodLog(true);
            DirectoryInfo KeyFolder = new DirectoryInfo(AppSettings.XXPKeysFolder);

            FileInfo[] files = KeyFolder.GetFiles("*.pem");
            int        count = files.Length;

            //string str = files[0].FullName;
            string PubKeyname = string.Format("pubkey{0}.pem", count / 2);
            string PriKeyname = string.Format("prikey{0}.pem", count / 2);
            string pubPath    = Path.Combine(AppSettings.XXPKeysFolder, PubKeyname);
            string priPath    = Path.Combine(AppSettings.XXPKeysFolder, PriKeyname);

            Cryptor.generateRSAKey2File(pubPath, priPath);
            this.dicKey2Hash.Add(PubKeyname, pubkey2Hash(pubPath));
            List <UTXO> lsteTmp = new List <UTXO>();

            this.dicComitkeysUtxoList.Add(PubKeyname, lsteTmp);
            this.dicUnComitkeysUtxoList.Add(PubKeyname, lsteTmp);
            LogHelper.WriteInfoLog("GernerateKeypairs Create:" + PubKeyname);
            return(PubKeyname);
        }
Exemple #23
0
        /**
         * @return true if:
         * (1) all outputs claimed by {@code tx} are in the current UTXO pool,
         * (2) the signatures on each input of {@code tx} are valid,
         * (3) no UTXO is claimed multiple times by {@code tx},
         * (4) all of {@code tx}s output values are non-negative, and
         * (5) the sum of {@code tx}s input values is greater than or equal to the sum of its output
         *     values; and false otherwise.
         */
        public bool isValidTx(Transaction tx)
        {
            LogHelper.WriteMethodLog(true);
            if (tx.listInputs.Count == 0 || tx.listOutputs.Count == 0)
            {
                LogHelper.WriteInfoLog("empty input|output");
                return(false);
            }

            // IMPLEMENT THIS
            double sumOut = 0;
            double sumIn  = 0;

            Dictionary <string, UTXO> dicUsed = new Dictionary <string, UTXO>();

            for (int i = 0; i < tx.numInputs(); i++)
            {
                Input input = tx.getInput(i);

                UTXO utxo = new UTXO(input.PreTxHash, (uint)input.OutputIndex);
                if (!CommitedUtxoPool.contains(utxo))
                {
                    LogHelper.WriteInfoLog(" utxoPool not contain utxo:");
                    return(false); //check (1),utox 包含该交易返回false
                }

                Output PreOutput = CommitedUtxoPool.getTxOutput(utxo); // the consume coin correspond prev output coin;
                sumIn += PreOutput.value;                              //(5) 计算input 指向的pre output 的value,最后保证输入的value等于该笔交易输出的
                string strOriginalTxt = tx.getRawDataToSign(i);
                if (!Cryptor.VerifySignature(input.ScriptSig, PreOutput.scriptPubKey, strOriginalTxt))
                {
                    LogHelper.WriteInfoLog(" VerifySignature fail");
                    return(false);//check(2)
                }


                bool bIsContain = dicUsed.ContainsKey(utxo.utoxHashCode());
                if (!bIsContain) // UTXO不会被重复添加
                {
                    dicUsed.Add(utxo.utoxHashCode(), utxo);
                }
                else
                {
                    LogHelper.WriteInfoLog(" double spend :" + utxo.utoxHashCode());
                    return(false);
                }
            }
            foreach (Output output in tx.getOutputs())
            {
                if (output.value < 0)
                {
                    LogHelper.WriteInfoLog(" output.value < 0 ");
                    return(false);//check(5)
                }
                sumOut += output.value;
            }
            if (sumIn < sumOut)
            {
                LogHelper.WriteInfoLog(" sumIn < sumOut ");
                return(false);//check(5);
            }
            LogHelper.WriteInfoLog("Valid Tx");
            return(true);
        }
Exemple #24
0
        public string SignPrimitiveTx(Dictionary <string, keyPair> KeyHashKeypair, ref Transaction PrimitiveTx)
        {
            LogHelper.WriteMethodLog(true);
            bool bHaveSigned = true;

            foreach (var item in PrimitiveTx.listInputs)
            {
                // 只要input有一个没有签名list,就认为没有签名
                if (item.lstScriptSig == null)
                {
                    bHaveSigned = false;
                    break;
                }
                else
                {   // 有签名list后 判断自己是否已经签名,
                    bHaveSigned = false;
                    foreach (var item1 in item.lstScriptSig)
                    {
                        string strKeyHash = Cryptor.SHA256(item1.PubKey, item1.PubKey.Length);
                        if (KeyHashKeypair.ContainsKey(strKeyHash))
                        {
                            bHaveSigned = true;
                        }
                    }
                }
            }
            if (bHaveSigned)
            {
                return("Current Primitive Tx'inputs Have signed");
            }

            int iInputCount = PrimitiveTx.listInputs.Count;

            for (int i = 0; i < iInputCount; i++)
            {
                UTXO utxo = new UTXO(PrimitiveTx.listInputs[i].PreTxHash, (uint)PrimitiveTx.listInputs[i].OutputIndex);

                if (!CommitedUtxoPool.contains(utxo))
                {
                    LogHelper.WriteInfoLog(" utxoPool not contain utxo:");
                    return("Invalid utxo"); //check (1),utox 包含该交易返回false
                }
                Output        output    = CommitedUtxoPool.getTxOutput(utxo);
                List <string> lstScript = output.scriptPubKey.Split(' ').ToList <string>();

                var lstPKHash = (from x in lstScript
                                 where x.Substring(0, 3) != "OP_"
                                 select x).ToList();


                foreach (var item in lstPKHash)
                {
                    if (KeyHashKeypair.ContainsKey(item))
                    {
                        keyPair kp = new keyPair();
                        KeyHashKeypair.TryGetValue(item, out kp);
                        string strPriKPath = Path.Combine(AppSettings.XXPKeysFolder, kp.PriKeyNmae);
                        string strPubKPath = Path.Combine(AppSettings.XXPKeysFolder, kp.PubKeyNmae);
                        string strPubValue = FileIOHelper.ReadFromText(strPubKPath);
                        PrimitiveTx.MultiSignTrans(strPriKPath, strPubValue, i);
                    }
                }
            }
            LogHelper.WriteMethodLog(false);
            return(ConstHelper.BC_OK);
        }