private IList<ICoin> GetCoins(ICoin coin, int numberOfCoins) { IList<ICoin> coins = new List<ICoin>(); for (int i = 0; i < numberOfCoins; i++) { coins.Add(coin); } return coins; }
public TransactionPolicyError[] Check(Transaction transaction, ICoin[] spentCoins) { spentCoins = spentCoins ?? new ICoin[0]; List<TransactionPolicyError> errors = new List<TransactionPolicyError>(); if(transaction.Version > Transaction.CURRENT_VERSION || transaction.Version < 1) { errors.Add(new TransactionPolicyError("Invalid transaction version, expected " + Transaction.CURRENT_VERSION)); } var dups = transaction.Inputs.AsIndexedInputs().GroupBy(i => i.PrevOut); foreach(var dup in dups) { var duplicates = dup.ToArray(); if(duplicates.Length != 1) errors.Add(new DuplicateInputPolicyError(duplicates)); } foreach(var input in transaction.Inputs.AsIndexedInputs()) { var coin = spentCoins.FirstOrDefault(s => s.Outpoint == input.PrevOut); if(coin == null) { errors.Add(new CoinNotFoundPolicyError(input)); } } foreach(var output in transaction.Outputs.AsCoins()) { if(output.Amount < Money.Zero) errors.Add(new OutputPolicyError("Output value should not be less than zero", (int)output.Outpoint.N)); } var fees = transaction.GetFee(spentCoins); if(fees != null) { if(fees < Money.Zero) errors.Add(new NotEnoughFundsPolicyError("Not enough funds in this transaction", -fees)); } return errors.ToArray(); }
public OpenChannelMessage OpenChannel(ICoin[] fundingCoins, Key[] fundingKeys, Key payerKey) { if(payerKey.PubKey != Arguments.Payer.PaymentPubKey) throw new ArgumentException("Invalid payerKey", "payerKey"); var p2sh = Arguments.Redeem.Hash.ScriptPubKey; var builder = new TransactionBuilder(); Fund = builder .AddCoins(fundingCoins) .AddKeys(fundingKeys) .Send(p2sh, Arguments.GetFundAmount()) .SetChange(Arguments.Payer.ScriptPubkey) .SendFees(Arguments.Fees) .Shuffle() .BuildTransaction(true); if(!builder.Verify(Fund, Arguments.Fees)) throw new MicroPaymentException("Funding transaction incorreclty signed"); var fundCoin = Fund.Outputs.AsCoins().First(c => c.ScriptPubKey == p2sh).ToScriptCoin(Arguments.Redeem); var unsignedRefund = Arguments.CreatePayment(Arguments.Fees, fundCoin); unsignedRefund.LockTime = Arguments.Expiration; builder = new TransactionBuilder() .AddKeys(payerKey) .AddCoins(fundCoin); Refund = builder.SignTransaction(unsignedRefund); return new OpenChannelMessage() { UnsignedRefund = unsignedRefund }; }
public void Pick(ref string line, IMineContext mineContext) { try { InitOnece(); if (string.IsNullOrEmpty(line)) { return; } // 使用Claymore挖非ETH币种时它也打印ETH,所以这里需要纠正它 if ("Claymore".Equals(mineContext.Kernel.Code, StringComparison.OrdinalIgnoreCase)) { if (mineContext.MainCoin.Code != "ETH" && line.Contains("ETH")) { line = line.Replace("ETH", mineContext.MainCoin.Code); } } ICoin coin = mineContext.MainCoin; bool isDual = false; Guid poolId = mineContext.MainCoinPool.GetId(); // 如果是双挖上下文且当前输入行中没有主币关键字则视为双挖币 if ((mineContext is IDualMineContext dualMineContext) && !line.Contains(mineContext.MainCoin.Code)) { isDual = true; coin = dualMineContext.DualCoin; poolId = dualMineContext.DualCoinPool.GetId(); } INTMinerContext root = NTMinerContext.Instance; // 这些方法输出的是事件消息 PickTotalSpeed(root, line, mineContext.KernelOutput, isDual); PickGpuSpeed(root, mineContext, line, mineContext.KernelOutput, isDual); PickTotalShare(root, line, mineContext.KernelOutput, coin, isDual); PickAcceptShare(root, line, mineContext.KernelOutput, coin, isDual); PickAcceptOneShare(root, mineContext, line, _preline, mineContext.KernelOutput, coin, isDual); PickRejectPattern(root, line, mineContext.KernelOutput, coin, isDual); PickRejectOneShare(root, mineContext, line, _preline, mineContext.KernelOutput, coin, isDual); PickRejectPercent(root, line, mineContext.KernelOutput, coin, isDual); PickPoolDelay(line, mineContext.KernelOutput, isDual, poolId); if (!isDual) { // 决定不支持双挖的单卡份额统计 PicFoundOneShare(root, mineContext, line, _preline, mineContext.KernelOutput); PicGotOneIncorrectShare(root, mineContext, line, _preline, mineContext.KernelOutput); } // 如果是像BMiner那样的主币和双挖币的输出在同一行那样的模式则一行输出既要视为主币又要视为双挖币 if (isDual && mineContext.KernelOutput.IsDualInSameLine) { coin = mineContext.MainCoin; isDual = false; PickTotalSpeed(root, line, mineContext.KernelOutput, isDual); PickGpuSpeed(root, mineContext, line, mineContext.KernelOutput, isDual); PickTotalShare(root, line, mineContext.KernelOutput, coin, isDual); PickAcceptShare(root, line, mineContext.KernelOutput, coin, isDual); PickAcceptOneShare(root, mineContext, line, _preline, mineContext.KernelOutput, coin, isDual); PickRejectPattern(root, line, mineContext.KernelOutput, coin, isDual); PickRejectOneShare(root, mineContext, line, _preline, mineContext.KernelOutput, coin, isDual); PickRejectPercent(root, line, mineContext.KernelOutput, coin, isDual); PickPoolDelay(line, mineContext.KernelOutput, isDual, poolId); } _preline = line; } catch (Exception e) { Logger.ErrorDebugLine(e); } }
public void MakeSelectedDualCoin(ICoin coin) { m_selected_dual_coin = coin; }
private void Init(INTMinerContext root) { var minerProfileRepository = root.ServerContext.CreateLocalRepository <MinerProfileData>(); _data = minerProfileRepository.GetAll().FirstOrDefault(); var mineWorkRepository = root.ServerContext.CreateLocalRepository <MineWorkData>(); MineWork = mineWorkRepository.GetAll().FirstOrDefault(); if (_data == null) { Guid coinId = Guid.Empty; ICoin coin = root.ServerContext.CoinSet.AsEnumerable().OrderBy(a => a.Code).FirstOrDefault(); if (coin != null) { coinId = coin.GetId(); } _data = MinerProfileData.CreateDefaultData(coinId); } else { // 交换到注册表以供守护进程访问 if (ClientAppType.IsMinerClient && !NTMinerContext.IsJsonLocal) { SetIsOuterUserEnabled(_data.IsOuterUserEnabled); SetOuterUserId(_data.OuterUserId); } } if (!_data.IsAutoStart && NTMinerRegistry.GetIsAutoStart()) { _data.IsAutoStart = true; minerProfileRepository.Update(_data); } if (_coinProfileSet == null) { _coinProfileSet = new CoinProfileSet(root); } else { _coinProfileSet.Refresh(); } if (_coinKernelProfileSet == null) { _coinKernelProfileSet = new CoinKernelProfileSet(root); } else { _coinKernelProfileSet.Refresh(); } if (_poolProfileSet == null) { _poolProfileSet = new PoolProfileSet(root); } else { _poolProfileSet.Refresh(); } if (_walletSet == null) { _walletSet = new WalletSet(root); } else { _walletSet.Refresh(); } }
public void AddCoin(ICoin c) { Coins.Add(c); }
public void CanEstimateFees() { var alice = new Key(); var bob = new Key(); var satoshi = new Key(); var bobAlice = PayToMultiSigTemplate.Instance.GenerateScriptPubKey(2, alice.PubKey, bob.PubKey); //Alice sends money to bobAlice //Bob sends money to bobAlice //bobAlice sends money to satoshi var aliceCoins = new ICoin[] { RandomCoin("0.4", alice), RandomCoin("0.6", alice) }; var bobCoins = new ICoin[] { RandomCoin("0.2", bob), RandomCoin("0.3", bob) }; var bobAliceCoins = new ICoin[] { RandomCoin("1.5", bobAlice, false), RandomCoin("0.25", bobAlice, true) }; TransactionBuilder builder = new TransactionBuilder(); builder.StandardTransactionPolicy = EasyPolicy; var unsigned = builder .AddCoins(aliceCoins) .Send(bobAlice, "1.0") .Then() .AddCoins(bobCoins) .Send(bobAlice, "0.5") .Then() .AddCoins(bobAliceCoins) .Send(satoshi.PubKey, "1.74") .SetChange(bobAlice) .BuildTransaction(false); builder.AddKeys(alice, bob, satoshi); var signed = builder.BuildTransaction(true); Assert.True(builder.Verify(signed)); Assert.True(Math.Abs(signed.ToBytes().Length - builder.EstimateSize(unsigned)) < 20); var rate = new FeeRate(Money.Coins(0.0004m)); var estimatedFees = builder.EstimateFees(unsigned, rate); builder.SendEstimatedFees(rate); signed = builder.BuildTransaction(true); Assert.True(builder.Verify(signed, estimatedFees)); }
public void CanSplitFees() { var satoshi = new Key(); var alice = new Key(); var bob = new Key(); var aliceCoins = new ICoin[] { RandomCoin("0.4", alice), RandomCoin("0.6", alice) }; var bobCoins = new ICoin[] { RandomCoin("0.2", bob), RandomCoin("0.3", bob) }; TransactionBuilder builder = new TransactionBuilder(); FeeRate rate = new FeeRate(Money.Coins(0.0004m)); var tx = builder .AddCoins(aliceCoins) .AddKeys(alice) .Send(satoshi, Money.Coins(0.1m)) .SetChange(alice) .Then() .AddCoins(bobCoins) .AddKeys(bob) .Send(satoshi, Money.Coins(0.01m)) .SetChange(bob) .SendEstimatedFeesSplit(rate) .BuildTransaction(true); var estimated = builder.EstimateFees(tx, rate); Assert.True(builder.Verify(tx, estimated)); }
public WitScriptCoin(ICoin coin, Script witRedeem) : base(coin.Outpoint, coin.TxOut) { SetAll(coin.TxOut.ScriptPubKey, witRedeem); }
public static uint256 SignatureHash(ICoin coin, Transaction txTo, SigHash nHashType = SigHash.All) { return(txTo.GetSignatureHash(coin, nHashType)); }
public TransactionBuilderSigner(ICoin coin, SigHash sigHash, IndexedTxIn txIn) { this.coin = coin; this.sigHash = sigHash; this.txIn = txIn; }
private Script CreateScriptSig(TransactionSigningContext ctx, ICoin coin, IndexedTxIn txIn) { var scriptPubKey = coin.GetScriptCode(); var keyRepo = new TransactionBuilderKeyRepository(this, ctx); var signer = new TransactionBuilderSigner(coin, ctx.SigHash, txIn); foreach(var extension in Extensions) { if(extension.CanGenerateScriptSig(scriptPubKey)) { return extension.GenerateScriptSig(scriptPubKey, keyRepo, signer); } } throw new NotSupportedException("Unsupported scriptPubKey"); }
private Script CombineScriptSigs(ICoin coin, Script a, Script b) { var scriptPubkey = coin.GetScriptCode(); if(Script.IsNullOrEmpty(a)) return b ?? Script.Empty; if(Script.IsNullOrEmpty(b)) return a ?? Script.Empty; foreach(var extension in Extensions) { if(extension.CanCombineScriptSig(scriptPubkey, a, b)) { return extension.CombineScriptSig(scriptPubkey, a, b); } } return a.Length > b.Length ? a : b; //Heurestic }
private void Sign(TransactionSigningContext ctx, ICoin coin, IndexedTxIn txIn) { var input = txIn.TxIn; if(coin is StealthCoin) { var stealthCoin = (StealthCoin)coin; var scanKey = FindKey(ctx, stealthCoin.Address.ScanPubKey.ScriptPubKey); if(scanKey == null) throw new KeyNotFoundException("Scan key for decrypting StealthCoin not found"); var spendKeys = stealthCoin.Address.SpendPubKeys.Select(p => FindKey(ctx, p.ScriptPubKey)).Where(p => p != null).ToArray(); ctx.AdditionalKeys.AddRange(stealthCoin.Uncover(spendKeys, scanKey)); var normalCoin = new Coin(coin.Outpoint, coin.TxOut); if(stealthCoin.Redeem != null) normalCoin = normalCoin.ToScriptCoin(stealthCoin.Redeem); coin = normalCoin; } var scriptSig = CreateScriptSig(ctx, coin, txIn); if(scriptSig == null) return; ScriptCoin scriptCoin = coin as ScriptCoin; Script signatures = null; if(coin.GetHashVersion() == HashVersion.Witness) { signatures = txIn.WitScript; if(scriptCoin != null) { if(scriptCoin.IsP2SH) txIn.ScriptSig = Script.Empty; if(scriptCoin.RedeemType == RedeemType.WitnessV0) signatures = RemoveRedeem(signatures); } } else { signatures = txIn.ScriptSig; if(scriptCoin != null && scriptCoin.RedeemType == RedeemType.P2SH) signatures = RemoveRedeem(signatures); } signatures = CombineScriptSigs(coin, scriptSig, signatures); if(coin.GetHashVersion() == HashVersion.Witness) { txIn.WitScript = signatures; if(scriptCoin != null) { if(scriptCoin.IsP2SH) txIn.ScriptSig = new Script(Op.GetPushOp(scriptCoin.GetP2SHRedeem().ToBytes(true))); if(scriptCoin.RedeemType == RedeemType.WitnessV0) txIn.WitScript = txIn.WitScript + new WitScript(Op.GetPushOp(scriptCoin.Redeem.ToBytes(true))); } } else { txIn.ScriptSig = signatures; if(scriptCoin != null && scriptCoin.RedeemType == RedeemType.P2SH) { txIn.ScriptSig = input.ScriptSig + Op.GetPushOp(scriptCoin.GetP2SHRedeem().ToBytes(true)); } } }
private int EstimateScriptSigSize(ICoin coin) { if(coin is IColoredCoin) coin = ((IColoredCoin)coin).Bearer; int size = 0; if(coin is ScriptCoin) { var scriptCoin = (ScriptCoin)coin; coin = new Coin(scriptCoin.Outpoint, new TxOut(scriptCoin.Amount, scriptCoin.Redeem)); size += new Script(Op.GetPushOp(scriptCoin.Redeem.ToBytes(true))).Length; } var scriptPubkey = coin.GetScriptCode(); foreach(var extension in Extensions) { if(extension.CanEstimateScriptSigSize(scriptPubkey)) { size += extension.EstimateScriptSigSize(scriptPubkey); return size; } } size += coin.TxOut.ScriptPubKey.Length; //Using heurestic to approximate size of unknown scriptPubKey return size; }
private static void PickRejectOneShare(INTMinerContext root, IMineContext mineContext, string input, string preline, IKernelOutput kernelOutput, ICoin coin, bool isDual) { string rejectOneShare = kernelOutput.RejectOneShare; if (isDual) { rejectOneShare = kernelOutput.DualRejectOneShare; } if (string.IsNullOrEmpty(rejectOneShare)) { return; } if (rejectOneShare.Contains("\n")) { input = preline + "\n" + input; } Regex regex = VirtualRoot.GetRegex(rejectOneShare); var match = regex.Match(input); if (match.Success) { if (!isDual) { // 决定不支持双挖的单卡份额统计 string gpuText = match.Groups[NTKeyword.GpuIndexGroupName].Value; if (!string.IsNullOrEmpty(gpuText)) { if (int.TryParse(gpuText, out int gpuIndex)) { if (kernelOutput.IsMapGpuIndex && !string.IsNullOrWhiteSpace(mineContext.KernelInput.DevicesArg)) { if (mineContext.UseDevices.Length != 0 && mineContext.UseDevices.Length != root.GpuSet.Count && gpuIndex < mineContext.UseDevices.Length) { gpuIndex = mineContext.UseDevices[gpuIndex]; } } if (string.IsNullOrEmpty(kernelOutput.FoundOneShare)) { root.GpusSpeed.IncreaseFoundShare(gpuIndex); } root.GpusSpeed.IncreaseRejectShare(gpuIndex); } } } ICoinShare share = root.CoinShareSet.GetOrCreate(coin.GetId()); root.CoinShareSet.UpdateShare(coin.GetId(), null, share.RejectShareCount + 1, DateTime.Now); } }
public override bool Equals(object obj) { ICoin c = obj as ICoin; return(Name == c?.Name); }
public void AddCoin(ICoin coin) { Coins.Add(coin); NumberOfTimesAddCoinWasCalled++; CoinsPassedToAddCoin.Add(coin); }
public static SpeedData CreateSpeedData() { INTMinerRoot root = NTMinerRoot.Instance; IWorkProfile workProfile = root.MinerProfile; string macAddress = string.Empty; string localIp = string.Empty; foreach (var item in VirtualRoot.LocalIpSet.AsEnumerable()) { if (macAddress.Length != 0) { macAddress += "," + item.MACAddress; localIp += "," + item.IPAddress; } else { macAddress = item.MACAddress; localIp = item.IPAddress; } } SpeedData data = new SpeedData { LocalServerMessageTimestamp = VirtualRoot.LocalServerMessageSetTimestamp, KernelSelfRestartCount = 0, IsAutoBoot = workProfile.IsAutoBoot, IsAutoStart = workProfile.IsAutoStart, AutoStartDelaySeconds = workProfile.AutoStartDelaySeconds, Version = MainAssemblyInfo.CurrentVersion.ToString(4), BootOn = root.CreatedOn, MineStartedOn = null, IsMining = root.IsMining, MineWorkId = Guid.Empty, MineWorkName = string.Empty, MinerName = workProfile.MinerName, GpuInfo = root.GpuSetInfo, ClientId = VirtualRoot.Id, MACAddress = macAddress, LocalIp = localIp, MainCoinCode = string.Empty, MainCoinWallet = string.Empty, MainCoinTotalShare = 0, MainCoinRejectShare = 0, MainCoinSpeed = 0, DualCoinCode = string.Empty, DualCoinTotalShare = 0, DualCoinRejectShare = 0, DualCoinSpeed = 0, DualCoinPool = string.Empty, DualCoinWallet = string.Empty, IsDualCoinEnabled = false, Kernel = string.Empty, MainCoinPool = string.Empty, OSName = Windows.OS.Instance.WindowsEdition, GpuDriver = root.GpuSet.DriverVersion.ToString(), GpuType = root.GpuSet.GpuType, OSVirtualMemoryMb = NTMinerRoot.OSVirtualMemoryMb, KernelCommandLine = string.Empty, DiskSpace = NTMinerRoot.DiskSpace, IsAutoRestartKernel = workProfile.IsAutoRestartKernel, AutoRestartKernelTimes = workProfile.AutoRestartKernelTimes, IsNoShareRestartKernel = workProfile.IsNoShareRestartKernel, NoShareRestartKernelMinutes = workProfile.NoShareRestartKernelMinutes, IsNoShareRestartComputer = workProfile.IsNoShareRestartComputer, NoShareRestartComputerMinutes = workProfile.NoShareRestartComputerMinutes, IsPeriodicRestartComputer = workProfile.IsPeriodicRestartComputer, PeriodicRestartComputerHours = workProfile.PeriodicRestartComputerHours, IsPeriodicRestartKernel = workProfile.IsPeriodicRestartKernel, PeriodicRestartKernelHours = workProfile.PeriodicRestartKernelHours, PeriodicRestartComputerMinutes = workProfile.PeriodicRestartComputerMinutes, PeriodicRestartKernelMinutes = workProfile.PeriodicRestartKernelMinutes, IsAutoStartByCpu = workProfile.IsAutoStartByCpu, IsAutoStopByCpu = workProfile.IsAutoStopByCpu, CpuGETemperatureSeconds = workProfile.CpuGETemperatureSeconds, CpuLETemperatureSeconds = workProfile.CpuLETemperatureSeconds, CpuStartTemperature = workProfile.CpuStartTemperature, CpuStopTemperature = workProfile.CpuStopTemperature, MainCoinPoolDelay = string.Empty, DualCoinPoolDelay = string.Empty, MinerIp = string.Empty, IsFoundOneGpuShare = false, IsGotOneIncorrectGpuShare = false, IsRejectOneGpuShare = false, CpuPerformance = root.CpuPackage.Performance, CpuTemperature = root.CpuPackage.Temperature, IsRaiseHighCpuEvent = workProfile.IsRaiseHighCpuEvent, HighCpuPercent = workProfile.HighCpuBaseline, HighCpuSeconds = workProfile.HighCpuSeconds, GpuTable = root.GpusSpeed.AsEnumerable().Where(a => a.Gpu.Index != NTMinerRoot.GpuAllId).Select(a => a.ToGpuSpeedData()).ToArray() }; if (workProfile.MineWork != null) { data.MineWorkId = workProfile.MineWork.GetId(); data.MineWorkName = workProfile.MineWork.Name; } #region 当前选中的币种是什么 if (root.ServerContext.CoinSet.TryGetCoin(workProfile.CoinId, out ICoin mainCoin)) { data.MainCoinCode = mainCoin.Code; ICoinProfile coinProfile = workProfile.GetCoinProfile(mainCoin.GetId()); data.MainCoinWallet = coinProfile.Wallet; if (root.ServerContext.PoolSet.TryGetPool(coinProfile.PoolId, out IPool mainCoinPool)) { data.MainCoinPool = mainCoinPool.Server; if (root.IsMining) { data.MainCoinPoolDelay = root.ServerContext.PoolSet.GetPoolDelayText(mainCoinPool.GetId(), isDual: false); } if (mainCoinPool.IsUserMode) { IPoolProfile mainCoinPoolProfile = workProfile.GetPoolProfile(coinProfile.PoolId); data.MainCoinWallet = mainCoinPoolProfile.UserName; } } else { data.MainCoinPool = string.Empty; } if (root.ServerContext.CoinKernelSet.TryGetCoinKernel(coinProfile.CoinKernelId, out ICoinKernel coinKernel)) { if (root.ServerContext.KernelSet.TryGetKernel(coinKernel.KernelId, out IKernel kernel)) { data.Kernel = kernel.GetFullName(); if (root.ServerContext.KernelOutputSet.TryGetKernelOutput(kernel.KernelOutputId, out IKernelOutput kernelOutput)) { data.IsFoundOneGpuShare = !string.IsNullOrEmpty(kernelOutput.FoundOneShare); data.IsGotOneIncorrectGpuShare = !string.IsNullOrEmpty(kernelOutput.GpuGotOneIncorrectShare); data.IsRejectOneGpuShare = !string.IsNullOrEmpty(kernelOutput.RejectOneShare); } ICoinKernelProfile coinKernelProfile = workProfile.GetCoinKernelProfile(coinProfile.CoinKernelId); data.IsDualCoinEnabled = coinKernelProfile.IsDualCoinEnabled; if (coinKernelProfile.IsDualCoinEnabled) { if (root.ServerContext.CoinSet.TryGetCoin(coinKernelProfile.DualCoinId, out ICoin dualCoin)) { data.DualCoinCode = dualCoin.Code; ICoinProfile dualCoinProfile = workProfile.GetCoinProfile(dualCoin.GetId()); data.DualCoinWallet = dualCoinProfile.DualCoinWallet; if (root.ServerContext.PoolSet.TryGetPool(dualCoinProfile.DualCoinPoolId, out IPool dualCoinPool)) { data.DualCoinPool = dualCoinPool.Server; if (root.IsMining) { data.DualCoinPoolDelay = root.ServerContext.PoolSet.GetPoolDelayText(dualCoinPool.GetId(), isDual: true); } if (dualCoinPool.IsUserMode) { IPoolProfile dualCoinPoolProfile = workProfile.GetPoolProfile(dualCoinProfile.DualCoinPoolId); data.DualCoinWallet = dualCoinPoolProfile.UserName; } } else { data.DualCoinPool = string.Empty; } } } } } } #endregion if (root.IsMining) { var mineContext = root.LockedMineContext; if (mineContext != null) { data.KernelSelfRestartCount = mineContext.KernelSelfRestartCount; data.MineStartedOn = mineContext.CreatedOn; data.KernelCommandLine = mineContext.CommandLine; } // 判断上次报告的算力币种和本次报告的是否相同,否则说明刚刚切换了币种默认第一次报告0算力 if (_sLastSpeedMainCoin == null || _sLastSpeedMainCoin == root.LockedMineContext.MainCoin) { _sLastSpeedMainCoin = root.LockedMineContext.MainCoin; Guid coinId = root.LockedMineContext.MainCoin.GetId(); IGpusSpeed gpuSpeeds = NTMinerRoot.Instance.GpusSpeed; IGpuSpeed totalSpeed = gpuSpeeds.CurrentSpeed(NTMinerRoot.GpuAllId); data.MainCoinSpeed = totalSpeed.MainCoinSpeed.Value; ICoinShare share = root.CoinShareSet.GetOrCreate(coinId); data.MainCoinTotalShare = share.TotalShareCount; data.MainCoinRejectShare = share.RejectShareCount; } else { _sLastSpeedMainCoin = root.LockedMineContext.MainCoin; } if (root.LockedMineContext is IDualMineContext dualMineContext) { // 判断上次报告的算力币种和本次报告的是否相同,否则说明刚刚切换了币种默认第一次报告0算力 if (_sLastSpeedDualCoin == null || _sLastSpeedDualCoin == dualMineContext.DualCoin) { _sLastSpeedDualCoin = dualMineContext.DualCoin; Guid coinId = dualMineContext.DualCoin.GetId(); IGpusSpeed gpuSpeeds = NTMinerRoot.Instance.GpusSpeed; IGpuSpeed totalSpeed = gpuSpeeds.CurrentSpeed(NTMinerRoot.GpuAllId); data.DualCoinSpeed = totalSpeed.DualCoinSpeed.Value; ICoinShare share = root.CoinShareSet.GetOrCreate(coinId); data.DualCoinTotalShare = share.TotalShareCount; data.DualCoinRejectShare = share.RejectShareCount; } else { _sLastSpeedDualCoin = dualMineContext.DualCoin; } } } return(data); }
public void AddCoin(ICoin coin) { Coins.Add(coin); NotifyObservers(); }
public TransactionPolicyError[] Check(Transaction transaction, ICoin[] spentCoins) { if(transaction == null) throw new ArgumentNullException("transaction"); spentCoins = spentCoins ?? new ICoin[0]; List<TransactionPolicyError> errors = new List<TransactionPolicyError>(); foreach(var input in transaction.Inputs.AsIndexedInputs()) { var coin = spentCoins.FirstOrDefault(s => s.Outpoint == input.PrevOut); if(coin != null) { if(ScriptVerify != null) { ScriptError error; if(!VerifyScript(input, coin.TxOut.ScriptPubKey, ScriptVerify.Value, out error)) { errors.Add(new ScriptPolicyError(input, error, ScriptVerify.Value, coin.TxOut.ScriptPubKey)); } } } var txin = input.TxIn; if(txin.ScriptSig.Length > MaxScriptSigLength) { errors.Add(new InputPolicyError("Max scriptSig length exceeded actual is " + txin.ScriptSig.Length + ", max is " + MaxScriptSigLength, input)); } if(!txin.ScriptSig.IsPushOnly) { errors.Add(new InputPolicyError("All operation should be push", input)); } if(!txin.ScriptSig.HasCanonicalPushes) { errors.Add(new InputPolicyError("All operation should be canonical push", input)); } } foreach(var txout in transaction.Outputs.AsCoins()) { var template = StandardScripts.GetTemplateFromScriptPubKey(txout.ScriptPubKey); if(template == null) errors.Add(new OutputPolicyError("Non-Standard scriptPubKey", (int)txout.Outpoint.N)); } int txSize = transaction.GetSerializedSize(); if(MaxTransactionSize != null) { if(txSize >= MaxTransactionSize.Value) errors.Add(new TransactionSizePolicyError(txSize, MaxTransactionSize.Value)); } var fees = transaction.GetFee(spentCoins); if(fees != null) { if(CheckFee) { if(MaxTxFee != null) { var max = MaxTxFee.GetFee(txSize); if(fees > max) errors.Add(new FeeTooHighPolicyError(fees, max)); } if(MinRelayTxFee != null) { if(MinRelayTxFee != null) { var min = MinRelayTxFee.GetFee(txSize); if(fees < min) errors.Add(new FeeTooLowPolicyError(fees, min)); } } } } if(MinRelayTxFee != null) { foreach(var output in transaction.Outputs) { var bytes = output.ScriptPubKey.ToBytes(true); if(output.IsDust(MinRelayTxFee) && !IsOpReturn(bytes)) errors.Add(new DustPolicyError(output.Value, output.GetDustThreshold(MinRelayTxFee))); } } var opReturnCount = transaction.Outputs.Select(o => o.ScriptPubKey.ToBytes(true)).Count(b => IsOpReturn(b)); if(opReturnCount > 1) errors.Add(new TransactionPolicyError("More than one op return detected")); return errors.ToArray(); }
private void GetCoin(ICoin iCoin) { iCoin?.GetCoin(_fruitModel.coinValue); }
public Transaction SignTransaction(KeyPath keyPath, ICoin[] signedCoins, Transaction[] parents, Transaction transaction) { using(Transport.Lock()) { var pubkey = GetWalletPubKey(keyPath).UncompressedPublicKey.Compress(); var parentsById = parents.ToDictionary(p => p.GetHash()); var coinsByPrevout = signedCoins.ToDictionary(c => c.Outpoint); List<TrustedInput> trustedInputs = new List<TrustedInput>(); foreach(var input in transaction.Inputs) { Transaction parent; parentsById.TryGetValue(input.PrevOut.Hash, out parent); if(parent == null) throw new KeyNotFoundException("Parent transaction " + input.PrevOut.Hash + " not found"); trustedInputs.Add(GetTrustedInput(parent, (int)input.PrevOut.N)); } var inputs = trustedInputs.ToArray(); transaction = transaction.Clone(); foreach(var input in transaction.Inputs) { ICoin previousCoin = null; coinsByPrevout.TryGetValue(input.PrevOut, out previousCoin); if(previousCoin != null) input.ScriptSig = previousCoin.GetScriptCode(); } bool newTransaction = true; foreach(var input in transaction.Inputs.AsIndexedInputs()) { ICoin coin = null; if(!coinsByPrevout.TryGetValue(input.PrevOut, out coin)) continue; UntrustedHashTransactionInputStart(newTransaction, input, inputs); newTransaction = false; UntrustedHashTransactionInputFinalizeFull(transaction.Outputs); var sig = UntrustedHashSign(keyPath, null, transaction.LockTime, SigHash.All); input.ScriptSig = PayToPubkeyHashTemplate.Instance.GenerateScriptSig(sig, pubkey); ScriptError error; if(!Script.VerifyScript(coin.TxOut.ScriptPubKey, transaction, (int)input.Index, Money.Zero, out error)) return null; } return transaction; } }
public void Pick(ref string line, IMineContext mineContext) { try { InitOnece(); if (string.IsNullOrEmpty(line)) { return; } if (!string.IsNullOrEmpty(mineContext.KernelOutput.KernelRestartKeyword) && line.Contains(mineContext.KernelOutput.KernelRestartKeyword)) { if (_kernelRestartKeywordOn.AddSeconds(10) < DateTime.Now) { mineContext.KernelSelfRestartCount = mineContext.KernelSelfRestartCount + 1; _kernelRestartKeywordOn = DateTime.Now; VirtualRoot.RaiseEvent(new KernelSelfRestartedEvent()); } } ICoin coin = mineContext.MainCoin; bool isDual = false; Guid poolId = mineContext.MainCoinPool.GetId(); // 如果是双挖上下文且当前输入行中没有主币关键字则视为双挖币 if ((mineContext is IDualMineContext dualMineContext) && !line.Contains(mineContext.MainCoin.Code)) { isDual = true; coin = dualMineContext.DualCoin; poolId = dualMineContext.DualCoinPool.GetId(); } // 这些方法输出的是事件消息 PickTotalSpeed(_root, line, mineContext.KernelOutput, isDual); PickGpuSpeed(_root, mineContext, line, mineContext.KernelOutput, isDual); PickTotalShare(_root, line, mineContext.KernelOutput, coin, isDual); PickAcceptShare(_root, line, mineContext.KernelOutput, coin, isDual); PickAcceptOneShare(_root, mineContext, line, _preline, mineContext.KernelOutput, coin, isDual); PickRejectPattern(_root, line, mineContext.KernelOutput, coin, isDual); PickRejectOneShare(_root, mineContext, line, _preline, mineContext.KernelOutput, coin, isDual); PickRejectPercent(_root, line, mineContext.KernelOutput, coin, isDual); PickPoolDelay(line, mineContext.KernelOutput, isDual, poolId); if (!isDual) { // 决定不支持双挖的单卡份额统计 PicFoundOneShare(_root, mineContext, line, _preline, mineContext.KernelOutput); PicGotOneIncorrectShare(_root, mineContext, line, _preline, mineContext.KernelOutput); } // 如果是像BMiner那样的主币和双挖币的输出在同一行那样的模式则一行输出既要视为主币又要视为双挖币 if (isDual && mineContext.KernelOutput.IsDualInSameLine) { coin = mineContext.MainCoin; isDual = false; PickTotalSpeed(_root, line, mineContext.KernelOutput, isDual); PickGpuSpeed(_root, mineContext, line, mineContext.KernelOutput, isDual); PickTotalShare(_root, line, mineContext.KernelOutput, coin, isDual); PickAcceptShare(_root, line, mineContext.KernelOutput, coin, isDual); PickAcceptOneShare(_root, mineContext, line, _preline, mineContext.KernelOutput, coin, isDual); PickRejectPattern(_root, line, mineContext.KernelOutput, coin, isDual); PickRejectOneShare(_root, mineContext, line, _preline, mineContext.KernelOutput, coin, isDual); PickRejectPercent(_root, line, mineContext.KernelOutput, coin, isDual); PickPoolDelay(line, mineContext.KernelOutput, isDual, poolId); } _preline = line; } catch (Exception e) { Logger.ErrorDebugLine(e); } }
private void earn(ICoin coin) { Contract.Requires(_coins.Any(c => c.Ratio == coin.Ratio)); _coins.Where(c => c.Ratio == coin.Ratio).First().Add(coin.Amount); }
private static void PickTotalShare(INTMinerRoot root, string input, IKernelOutput kernelOutput, ICoin coin, bool isDual) { string totalSharePattern = kernelOutput.TotalSharePattern; if (isDual) { totalSharePattern = kernelOutput.DualTotalSharePattern; } if (string.IsNullOrEmpty(totalSharePattern)) { return; } Regex regex = VirtualRoot.GetRegex(totalSharePattern); var match = regex.Match(input); if (match.Success) { string totalShareText = match.Groups[VirtualRoot.TotalShareGroupName].Value; int totalShare; if (int.TryParse(totalShareText, out totalShare)) { ICoinShare share = root.CoinShareSet.GetOrCreate(coin.GetId()); root.CoinShareSet.UpdateShare(coin.GetId(), acceptShareCount: totalShare - share.RejectShareCount, rejectShareCount: null, now: DateTime.Now); } } }
public ICoin RemoveCoin(ICoin c) { Coins.Remove(c); return(c); }
public void UpdateFromCoin(ICoin coin) { if (coin == null) { throw new ArgumentNullException(nameof(coin)); } if (IsFinalized()) { throw new InvalidOperationException("Impossible to modify the PSBTInput if it has been finalized"); } if (coin.Outpoint != PrevOut) { throw new ArgumentException("This coin does not match the input", nameof(coin)); } if (coin is ScriptCoin scriptCoin) { if (scriptCoin.RedeemType == RedeemType.P2SH) { redeem_script = scriptCoin.Redeem; } else if (scriptCoin.RedeemType == RedeemType.WitnessV0) { witness_script = scriptCoin.Redeem; if (scriptCoin.IsP2SH) { redeem_script = witness_script.WitHash.ScriptPubKey; } } } else { if (coin.TxOut.ScriptPubKey.IsScriptType(ScriptType.P2SH) && redeem_script == null) { // Let's try to be smart by finding the redeemScript in the global tx if (Parent.Settings.IsSmart && redeem_script == null) { var redeemScript = PayToScriptHashTemplate.Instance.ExtractScriptSigParameters(originalScriptSig, coin.TxOut.ScriptPubKey)?.RedeemScript; if (redeemScript != null) { redeem_script = redeemScript; } } } if (witness_script == null) { // Let's try to be smart by finding the witness script in the global tx if (Parent.Settings.IsSmart && witness_script == null) { var witScriptId = PayToWitScriptHashTemplate.Instance.ExtractScriptPubKeyParameters(coin.TxOut.ScriptPubKey); if (witScriptId == null && redeem_script != null) { witScriptId = PayToWitScriptHashTemplate.Instance.ExtractScriptPubKeyParameters(redeem_script); } if (witScriptId != null) { var redeemScript = PayToWitScriptHashTemplate.Instance.ExtractWitScriptParameters(originalWitScript, witScriptId); if (redeemScript != null) { witness_script = redeemScript; } } } } } if (coin.GetHashVersion() == HashVersion.Witness || witness_script != null) { witness_utxo = coin.TxOut; non_witness_utxo = null; } else { orphanTxOut = coin.TxOut; witness_utxo = null; } }
public void MakeSelectedCoin(ICoin coin) { m_selected_coin = coin; }
public IEnumerable <WalletRule> GetMatchedRules(ICoin coin) { return(GetMatchedRules(coin.Outpoint)); }
public void InsertCoin(ICoin coin) { throw new NotImplementedException(); }
private static void PickRejectPattern(INTMinerContext root, string input, IKernelOutput kernelOutput, ICoin coin, bool isDual) { string rejectSharePattern = kernelOutput.RejectSharePattern; if (isDual) { rejectSharePattern = kernelOutput.DualRejectSharePattern; } if (string.IsNullOrEmpty(rejectSharePattern)) { return; } Regex regex = VirtualRoot.GetRegex(rejectSharePattern); var match = regex.Match(input); if (match.Success) { string rejectShareText = match.Groups[NTKeyword.RejectShareGroupName].Value; if (int.TryParse(rejectShareText, out int rejectShare)) { root.CoinShareSet.UpdateShare(coin.GetId(), acceptShareCount: null, rejectShareCount: rejectShare, now: DateTime.Now); } } }
public CryptoNoteMiner(string id, ICoin mainCoin, bool dualMining, ICoin dualCoin, string minerName, IMinerData minerData) : base(id, mainCoin, dualMining, dualCoin, minerName, minerData) { }
private static void PickRejectPercent(INTMinerContext root, string input, IKernelOutput kernelOutput, ICoin coin, bool isDual) { string rejectPercentPattern = kernelOutput.RejectPercentPattern; if (isDual) { rejectPercentPattern = kernelOutput.DualRejectPercentPattern; } if (string.IsNullOrEmpty(rejectPercentPattern)) { return; } Regex regex = VirtualRoot.GetRegex(rejectPercentPattern); var match = regex.Match(input); string rejectPercentText = match.Groups[NTKeyword.RejectPercentGroupName].Value; if (double.TryParse(rejectPercentText, out double rejectPercent)) { ICoinShare share = root.CoinShareSet.GetOrCreate(coin.GetId()); root.CoinShareSet.UpdateShare(coin.GetId(), acceptShareCount: null, rejectShareCount: (int)(share.TotalShareCount * rejectPercent), now: DateTime.Now); } }
public override bool CanEstimateScriptSigSize(ICoin coin) { return(CanSign(coin.GetScriptCode())); }
public ScriptCoin(ICoin coin, Script redeem) : base(coin.Outpoint, coin.TxOut) { Redeem = redeem; AssertCoherent(); }
public override int EstimateScriptSigSize(ICoin coin) { return(66); }
public TransactionPolicyError[] Check(Transaction transaction, ICoin[] spentCoins) { if (transaction == null) { throw new ArgumentNullException("transaction"); } spentCoins = spentCoins ?? new ICoin[0]; var errors = new List <TransactionPolicyError>(); foreach (IndexedTxIn input in transaction.Inputs.AsIndexedInputs()) { ICoin coin = spentCoins.FirstOrDefault(s => s.Outpoint == input.PrevOut); if (coin != null) { if (this.ScriptVerify != null) { if (!input.VerifyScript(this.network, coin.TxOut.ScriptPubKey, coin.TxOut.Value, this.ScriptVerify.Value, out ScriptError error)) { errors.Add(new ScriptPolicyError(input, error, this.ScriptVerify.Value, coin.TxOut.ScriptPubKey)); } } } TxIn txin = input.TxIn; if (txin.ScriptSig.Length > MaxScriptSigLength) { errors.Add(new InputPolicyError("Max scriptSig length exceeded actual is " + txin.ScriptSig.Length + ", max is " + MaxScriptSigLength, input)); } if (!txin.ScriptSig.IsPushOnly) { errors.Add(new InputPolicyError("All operation should be push", input)); } if (!txin.ScriptSig.HasCanonicalPushes) { errors.Add(new InputPolicyError("All operation should be canonical push", input)); } } if (this.CheckMalleabilitySafe) { foreach (IndexedTxIn input in transaction.Inputs.AsIndexedInputs()) { ICoin coin = spentCoins.FirstOrDefault(s => s.Outpoint == input.PrevOut); if (coin != null && coin.GetHashVersion(this.network) != HashVersion.Witness) { errors.Add(new InputPolicyError("Malleable input detected", input)); } } } CheckPubKey(transaction, errors); int txSize = transaction.GetSerializedSize(); if (this.MaxTransactionSize != null) { if (txSize >= this.MaxTransactionSize.Value) { errors.Add(new TransactionSizePolicyError(txSize, this.MaxTransactionSize.Value)); } } Money fees = transaction.GetFee(spentCoins); if (fees != null) { if (this.CheckFee) { if (this.MaxTxFee != null) { Money max = this.MaxTxFee.GetFee(txSize); if (fees > max) { errors.Add(new FeeTooHighPolicyError(fees, max)); } } if (this.MinRelayTxFee != null) { if (this.MinRelayTxFee != null) { Money min = this.MinRelayTxFee.GetFee(txSize); if (fees < min) { errors.Add(new FeeTooLowPolicyError(fees, min)); } } } } } this.CheckMinRelayTxFee(transaction, errors); int opReturnCount = transaction.Outputs.Select(o => o.ScriptPubKey.ToBytes(true)).Count(b => IsOpReturn(b)); if (opReturnCount > 1) { errors.Add(new TransactionPolicyError("More than one op return detected")); } return(errors.ToArray()); }
public override bool Match(ICoin coin, PSBTInput input) { return(coin.TxOut.ScriptPubKey.IsScriptType(ScriptType.Taproot) && PayToTaprootTemplate.Instance.CheckScriptPubKey(coin.TxOut.ScriptPubKey)); }
public KnowMore(ICoin coin) { m_Maincoin = coin; InitializeComponent(); }
public void AddCoin(ICoin c) { this.Coins.Add(c); }
public void RemoveCoin(ICoin c) { this.Coins.Remove(c); }
public IEnumerable<WalletRule> GetMatchedRules(ICoin coin) { return GetMatchedRules(coin.Outpoint); }
public bool IsValid(ICoin usCoin) { return((usCoin.Type() == CoinTypes.USNickel || usCoin.Type() == CoinTypes.USDime || usCoin.Type() == CoinTypes.USQuarter) ? true : false); }
//https://en.bitcoin.it/wiki/OP_CHECKSIG public static uint256 SignatureHash(ICoin coin, Transaction txTo, SigHash nHashType = SigHash.All) { var input = txTo.Inputs.AsIndexedInputs().FirstOrDefault(i => i.PrevOut == coin.Outpoint); if(input == null) throw new ArgumentException("coin should be spent spent in txTo", "coin"); return input.GetSignatureHash(coin, nHashType); }
public IMiner CreateMiner(ICoin mainCoin, bool dualMining, ICoin dualCoin, string minerName) { IMiner miner = CreateMiner(GenerateUniqueID(), mainCoin, dualMining, dualCoin, minerName, null); return(miner); }
public void CanSplitFees() { var satoshi = new Key(); var alice = new Key(); var bob = new Key(); var aliceCoins = new ICoin[] { RandomCoin("0.4", alice), RandomCoin("0.6", alice) }; var bobCoins = new ICoin[] { RandomCoin("0.2", bob), RandomCoin("0.3", bob) }; TransactionBuilder builder = new TransactionBuilder(); FeeRate rate = new FeeRate(Money.Coins(0.0004m)); var tx = builder .AddCoins(aliceCoins) .AddKeys(alice) .Send(satoshi, Money.Coins(0.1m)) .SetChange(alice) .Then() .AddCoins(bobCoins) .AddKeys(bob) .Send(satoshi, Money.Coins(0.01m)) .SetChange(bob) .SendEstimatedFeesSplit(rate) .BuildTransaction(true); var estimated = builder.EstimateFees(tx, rate); Assert.True(builder.Verify(tx, estimated)); // Alice should pay two times more fee than bob builder = new TransactionBuilder(); tx = builder .AddCoins(aliceCoins) .AddKeys(alice) .SetFeeWeight(2.0m) .Send(satoshi, Money.Coins(0.1m)) .SetChange(alice) .Then() .AddCoins(bobCoins) .AddKeys(bob) .Send(satoshi, Money.Coins(0.01m)) .SetChange(bob) .SendFeesSplit(Money.Coins(0.6m)) .BuildTransaction(true); var spentAlice = builder.FindSpentCoins(tx).Where(c => aliceCoins.Contains(c)).OfType<Coin>().Select(c => c.Amount).Sum(); var receivedAlice = tx.Outputs.AsCoins().Where(c => c.ScriptPubKey == alice.PubKey.Hash.ScriptPubKey).Select(c => c.Amount).Sum(); Assert.Equal(Money.Coins(0.1m + 0.4m), spentAlice - receivedAlice); var spentBob = builder.FindSpentCoins(tx).Where(c => bobCoins.Contains(c)).OfType<Coin>().Select(c => c.Amount).Sum(); var receivedBob = tx.Outputs.AsCoins().Where(c => c.ScriptPubKey == bob.PubKey.Hash.ScriptPubKey).Select(c => c.Amount).Sum(); Assert.Equal(Money.Coins(0.01m + 0.2m), spentBob - receivedBob); }
private IMiner CreateMiner(string id, ICoin mainCoin, bool dualMining, ICoin dualCoin, string minerName, IMinerData data) { IMiner miner = new MogMiner(id, mainCoin, dualMining, dualCoin, minerName, data); return(miner); }
public void Accept(ICoin coin) { if (coin.GetType().BaseType != typeof(UsCoin)) throw new InValidCoinException("MyCoinJar accepts only UsCoin"); if (this.TotalVolume.Unit < (this.actualVolume.Unit + coin.Volume.Unit)) throw new CoinOverFlowException(); coinHeap.Add(coin); actualVolume.Unit += coin.Volume.Unit; actualAmount.UnitPrice += coin.Value.UnitPrice; }
public void Spend(ICoin coin) { SpendGold(coin.NormalizedAmount); }