private static void Decrypt(IHashAlgorithm algo) { // IProducerConsumerCollection using (var producerConsumerCollection = new BlockingCollection<string>(50000)) { // Consumer. var tasks = new List<Task>(); for (int workingThread = 0; workingThread < Environment.ProcessorCount; workingThread++) { tasks.Add(Task.Factory.StartNew(() => HashThread(algo, producerConsumerCollection))); } // Producer. while (true) { var line = Console.ReadLine(); if (line == null) { producerConsumerCollection.CompleteAdding(); break; } producerConsumerCollection.Add(line); } // Wait until processing is done. foreach (Task task in tasks) { task.Wait(); } } }
/// <summary> /// Creates a new instance of JobNotification. /// </summary> /// <param name="id"></param> /// <param name="algorithm"></param> /// <param name="blockTemplate"></param> /// <param name="generationTransaction"></param> public Job(UInt64 id, IHashAlgorithm algorithm, IBlockTemplate blockTemplate, IGenerationTransaction generationTransaction) { // init the values. Id = id; HashAlgorithm = algorithm; BlockTemplate = blockTemplate; GenerationTransaction = generationTransaction; PreviousBlockHash = blockTemplate.PreviousBlockHash.HexToByteArray().ToHexString(); PreviousBlockHashReversed = blockTemplate.PreviousBlockHash.HexToByteArray().ReverseByteOrder().ToHexString(); CoinbaseInitial = generationTransaction.Initial.ToHexString(); CoinbaseFinal = generationTransaction.Final.ToHexString(); // calculate the merkle tree this.MerkleTree = new MerkleTree(BlockTemplate.Transactions.GetHashList()); // set version Version = BitConverter.GetBytes(blockTemplate.Version.BigEndian()).ToHexString(); // set the encoded difficulty (bits) EncodedDifficulty = blockTemplate.Bits; // set the target Target = string.IsNullOrEmpty(blockTemplate.Target) ? EncodedDifficulty.BigIntFromBitsHex() : BigInteger.Parse(blockTemplate.Target, NumberStyles.HexNumber); // set the block diff Difficulty = ((double)new BigRational(HashAlgorithm.Difficulty, Target)); // set the ntime nTime = BitConverter.GetBytes(blockTemplate.CurTime.BigEndian()).ToHexString(); }
void EnsureMetadata() { if (hasReadMetadata) return; reader.BaseStream.Seek(0, SeekOrigin.Begin); var first = reader.ReadBytes(BinaryFormat.DeltaHeader.Length); if (!StructuralComparisons.StructuralEqualityComparer.Equals(first, BinaryFormat.DeltaHeader)) throw new CorruptFileFormatException("The delta file appears to be corrupt."); var version = reader.ReadByte(); if (version != BinaryFormat.Version) throw new CorruptFileFormatException("The delta file uses a newer file format than this program can handle."); var hashAlgorithmName = reader.ReadString(); hashAlgorithm = SupportedAlgorithms.Hashing.Create(hashAlgorithmName); var hashLength = reader.ReadInt32(); expectedHash = reader.ReadBytes(hashLength); var endOfMeta = reader.ReadBytes(BinaryFormat.EndOfMetadata.Length); if (!StructuralComparisons.StructuralEqualityComparer.Equals(BinaryFormat.EndOfMetadata, endOfMeta)) throw new CorruptFileFormatException("The signature file appears to be corrupt."); hasReadMetadata = true; }
public void WriteMetadata(IHashAlgorithm hashAlgorithm, IRollingChecksum rollingChecksumAlgorithm, byte[] hash) { signatureStream.Write(BinaryFormat.SignatureHeader); signatureStream.Write(BinaryFormat.Version); signatureStream.Write(hashAlgorithm.Name); signatureStream.Write(rollingChecksumAlgorithm.Name); signatureStream.Write(BinaryFormat.EndOfMetadata); }
public CryptoService(ICryptoStore store, IHashAlgorithm hashAlgorithm, IEncryptionAlgorithm encryptionAlgorithm, IUserBasedDataProtection userBasedDataProtection) { _store = store; _hashAlgorithm = hashAlgorithm; _encryptionAlgorithm = encryptionAlgorithm; _userBasedDataProtection = userBasedDataProtection; }
public DeltaGenerator(IRollingChecksum checksumProvider, IHashAlgorithm hashProvider) { if (checksumProvider == null) throw new ArgumentNullException("checksumProvider"); if (hashProvider == null) throw new ArgumentNullException("hashProvider"); _initialized = false; ChecksumProvider = checksumProvider; HashProvider = hashProvider; }
public void WriteMetadata(IHashAlgorithm hashAlgorithm, byte[] expectedNewFileHash) { writer.Write(BinaryFormat.DeltaHeader); writer.Write(BinaryFormat.Version); writer.Write(hashAlgorithm.Name); writer.Write(expectedNewFileHash.Length); writer.Write(expectedNewFileHash); writer.Write(BinaryFormat.EndOfMetadata); }
public HashBlockGenerator(IRollingChecksum checksumProvider, IHashAlgorithm hashProvider, int blockSize) { if (checksumProvider == null) throw new ArgumentNullException("checksumProvider"); if (hashProvider == null) throw new ArgumentNullException("hashProvider"); if (blockSize <= 0) throw new ArgumentException("blockSize must be greater than zero"); ChecksumProvider = checksumProvider; HashAlgorithm = hashProvider; _blockSize = blockSize; }
/// <summary> /// Initializes a new instance of the <see cref="HashService"/> class with an Hashalgorithm. /// </summary> /// <param name="algorithm">The hashalgorithm.</param> /// <exception cref="ArgumentNullException"><paramref name="algorithm"/>is null</exception> public HashService(IHashAlgorithm algorithm) { if (algorithm == null) { throw new ArgumentNullException("algorithm", "Can't initialize hashservice without a hashalgorithm!"); } this.algorithm = algorithm; }
public HashCalculator(IHashAlgorithm method, SmartThreadPool pool) { _method = method; _pool = pool; if(_hashGroup == null) { _hashGroup = _pool.CreateWorkItemsGroup(1); } }
public JobManager(IDaemonClient daemonClient, IJobTracker jobTracker, IShareManager shareManager, IMinerManager minerManager, IHashAlgorithm hashAlgorithm) { _daemonClient = daemonClient; _jobTracker = jobTracker; _shareManager = shareManager; _minerManager = minerManager; _hashAlgorithm = hashAlgorithm; _jobCounter = new JobCounter(); }
public PerPool(IPoolConfig poolConfig, IDaemonClient daemonClient,IMinerManager minerManager, IHashAlgorithm hashAlgorithm, IBlocks blockStatistics, IStorage storage) { Config = poolConfig; _daemonClient = daemonClient; _minerManager = minerManager; Blocks = blockStatistics; _storage = storage; _response = new ExpandoObject(); _shareMultiplier = Math.Pow(2, 32) / hashAlgorithm.Multiplier; }
public NetworkInfo(IDaemonClient daemonClient, IHashAlgorithm hashAlgorithm, IPoolConfig poolConfig) { _daemonClient = daemonClient; _hashAlgorithm = hashAlgorithm; _poolConfig = poolConfig; _logger = Log.ForContext<NetworkInfo>().ForContext("Component", poolConfig.Coin.Name); DetectProofOfStakeCoin(); // detect if we are running on a proof-of-stake coin. DetectSubmitBlockSupport(); // detect if the coin daemon supports submitblock call. Recache(); // recache the data initially. PrintNetworkInfo(); // print the collected network info. }
/// <summary> /// Gets the specified daemon client. /// </summary> /// <param name="daemonClient">The daemon client.</param> /// <param name="jobTracker"></param> /// <param name="shareManager"></param> /// <param name="minerManager">The miner manager.</param> /// <param name="hashAlgorithm"></param> /// <returns></returns> public IJobManager Get(IDaemonClient daemonClient, IJobTracker jobTracker, IShareManager shareManager, IMinerManager minerManager, IHashAlgorithm hashAlgorithm) { var @params = new NamedParameterOverloads { {"daemonClient", daemonClient}, {"jobTracker", jobTracker}, {"shareManager", shareManager}, {"minerManager", minerManager}, {"hashAlgorithm", hashAlgorithm} }; return _applicationContext.Container.Resolve<IJobManager>(@params); }
public EncryptorImplementation(IAESAlgorithm algorithm, IHashAlgorithm hashAlgorithm, IFile fileSystem) { if(algorithm == null) throw new System.ArgumentNullException("algorithm"); if(hashAlgorithm == null) throw new System.ArgumentNullException("hashAlgorithm"); if(fileSystem == null) throw new System.ArgumentNullException("fileSystem"); Algorithm = algorithm; HashAlgorithm = hashAlgorithm; FileSystem = fileSystem; }
internal OneTimePassword(byte[] key, IHashAlgorithm hashAlgorithm, int? returnDigits = null) { if (returnDigits <= 0 || returnDigits > _iterationPowers.Length - 1) { StringBuilder msg = new StringBuilder(); msg.Append("The number of digits should be between 1 and "); msg.Append(_iterationPowers.Length); throw new ArgumentOutOfRangeException("digits", msg.ToString()); } this.secret = key; this.digits = returnDigits ?? MAXIMUM_DIGITS; this.digest = hashAlgorithm ?? new HashSha1(); }
public void SetUp() { this.mockery = new Mockery(); this.algorithm = this.mockery.NewMock<IHashAlgorithm>(); this.reader = this.mockery.NewMock<ITextReader>(); this.writer = this.mockery.NewMock<ITextWriter>(); this.hashReader = this.mockery.NewMock<ITextReader>(); this.testee = new HashService(this.algorithm); }
private Timer _reBroadcastTimer; // timer for rebroadcasting jobs after an pre-configured idle perioud. #endregion Fields #region Constructors public JobManager(IPoolConfig poolConfig, IDaemonClient daemonClient, IJobTracker jobTracker, IShareManager shareManager, IMinerManager minerManager, IHashAlgorithm hashAlgorithm) { _daemonClient = daemonClient; _jobTracker = jobTracker; _shareManager = shareManager; _minerManager = minerManager; _hashAlgorithm = hashAlgorithm; _poolConfig = poolConfig; _jobCounter = new JobCounter(); // todo make this ioc based too. _logger = Log.ForContext<JobManager>().ForContext("Component", poolConfig.Coin.Name); }
public JobManager(string pool, IDaemonClient daemonClient, IJobTracker jobTracker, IShareManager shareManager, IMinerManager minerManager, IHashAlgorithm hashAlgorithm, IWalletConfig walletConfig, IRewardsConfig rewardsConfig) { _daemonClient = daemonClient; _jobTracker = jobTracker; _shareManager = shareManager; _minerManager = minerManager; _hashAlgorithm = hashAlgorithm; _walletConfig = walletConfig; _rewardsConfig = rewardsConfig; _jobCounter = new JobCounter(); // todo make this ioc based too. _logger = Log.ForContext<JobManager>().ForContext("Component", pool); }
public DefaultCryptoService(ISymmetricAlgorithm symmetricAlgorithm, IHashAlgorithm hashAlgorithm) { if (symmetricAlgorithm == null) { throw new ArgumentNullException("symmetricAlgorithm"); } if (hashAlgorithm == null) { throw new ArgumentNullException("hashAlgorithm"); } this.symmetricAlgorithm = symmetricAlgorithm; this.hashAlgorithm = hashAlgorithm; }
public static string Hash(this IFileInfo fileInfo, IHashAlgorithm hashAlgorithm = null) { if (hashAlgorithm == null) { hashAlgorithm = Hashing.Default; } using (hashAlgorithm) { using (var stream = fileInfo.OpenRead()) { var hash = hashAlgorithm.ComputeHex(stream); return hash; } } }
private static void HashThread(IHashAlgorithm algo, BlockingCollection<string> producerConsumerCollection) { var hashAlgo = algo.CreateHashAlgorithm(); var taskOutputs = new StringBuilder(); int count = 0; while (!producerConsumerCollection.IsCompleted) { string line; try { line = producerConsumerCollection.Take(); } catch (InvalidOperationException) { if (producerConsumerCollection.IsCompleted) break; throw; } // Hash that line. byte[] inputBytes = Encoding.ASCII.GetBytes(line); byte[] hash = hashAlgo.ComputeHash(inputBytes); // Convert to hexadecimal. foreach (byte b in hash) { taskOutputs.Append(HexStringTable[b]); } taskOutputs.Append(' '); taskOutputs.AppendLine(line); // Output the hashed values in a batch. if (++count > 10000) { Console.Write(taskOutputs.ToString()); taskOutputs.Clear(); count = 0; } } // Output the last hashed values. Console.Write(taskOutputs.ToString()); }
public DefaultCryptoService(string secretKeyPassword, string initialVectorPassword, string hashKeyString) { if (secretKeyPassword == null) { throw new ArgumentNullException("secretKeyPassword"); } if (initialVectorPassword == null) { throw new ArgumentNullException("initialVectorPassword"); } if (hashKeyString == null) { throw new ArgumentNullException("hashKey"); } this.symmetricAlgorithm = new AES(secretKeyPassword, initialVectorPassword); this.hashAlgorithm = new HMACSHA512(hashKeyString); }
public CrytpoHashProvider(IFileSystem fileSystem, CryptoHashProviderType providerType) { _fileSystem = fileSystem; switch (providerType) { case CryptoHashProviderType.Md5: _hashAlgorithm = new HashAlgorithm(MD5.Create()); break; case CryptoHashProviderType.Sha1: _hashAlgorithm = new HashAlgorithm(SHA1.Create()); break; case CryptoHashProviderType.Sha256: _hashAlgorithm = new HashAlgorithm(SHA256.Create()); break; case CryptoHashProviderType.Sha512: _hashAlgorithm = new HashAlgorithm(SHA512.Create()); break; } }
public DefaultHttpMessageCryptoService(ISymmetricAlgorithm symmetricAlgorithm, IHashAlgorithm hashAlgorithm, ITimestampProvider<string> timestampProvider) { if (symmetricAlgorithm == null) { throw new ArgumentNullException("symmetricAlgorithm"); } if (hashAlgorithm == null) { throw new ArgumentNullException("hashAlgorithm"); } if (timestampProvider == null) { throw new ArgumentNullException("timestampProvider"); } this.symmetricAlgorithm = symmetricAlgorithm; this.hashAlgorithm = hashAlgorithm; this.timestampProvider = timestampProvider; }
public JobTests() { // daemon client _daemonClient = Substitute.For<IDaemonClient>(); _daemonClient.ValidateAddress(Arg.Any<string>()).Returns(new ValidateAddress { IsValid = true }); // block template const string json = "{\"result\":{\"version\":2,\"previousblockhash\":\"22a9174d9db64f1919febc9577167764c301b755768b675291f7d34454561e9e\",\"transactions\":[],\"coinbaseaux\":{\"flags\":\"062f503253482f\"},\"coinbasevalue\":5000000000,\"target\":\"0000002bd7c30000000000000000000000000000000000000000000000000000\",\"mintime\":1402922277,\"mutable\":[\"time\",\"transactions\",\"prevblock\"],\"noncerange\":\"00000000ffffffff\",\"sigoplimit\":20000,\"sizelimit\":1000000,\"curtime\":1402922598,\"bits\":\"1d2bd7c3\",\"height\":305349},\"error\":null,\"id\":1}"; var @object = JsonConvert.DeserializeObject<DaemonResponse<BlockTemplate>>(json); _blockTemplate = @object.Result; // extra nonce _extraNonce = new ExtraNonce(0); // signature script _signatureScript = new SignatureScript( _blockTemplate.Height, _blockTemplate.CoinBaseAux.Flags, 1402922597281, (byte) _extraNonce.ExtraNoncePlaceholder.Length, "/nodeStratum/"); // pool config _poolConfig = Substitute.For<IPoolConfig>(); // create coin config. var coinConfig = Substitute.For<ICoinConfig>(); coinConfig.Options.TxMessageSupported.Returns(false); coinConfig.Options.IsProofOfStakeHybrid.Returns(false); _poolConfig.Coin.Returns(coinConfig); // outputs _outputs = Substitute.For<Outputs>(_daemonClient, coinConfig); double blockReward = 5000000000; // the amount rewarded by the block. // create rewards config. var rewardsConfig = Substitute.For<IRewardsConfig>(); _poolConfig.Rewards.Returns(rewardsConfig); // create sample reward var amount = blockReward * 0.01; blockReward -= amount; var rewards = new Dictionary<string, float> { {"mrwhWEDnU6dUtHZJ2oBswTpEdbBHgYiMji", (float) amount} }; rewardsConfig.GetEnumerator().Returns(rewards.GetEnumerator()); foreach (var pair in rewards) { _outputs.AddRecipient(pair.Key, pair.Value); } // create wallet config. var walletConfig = Substitute.For<IWalletConfig>(); _poolConfig.Wallet.Returns(walletConfig); // create sample pool central wallet output. walletConfig.Adress.Returns("mk8JqN1kNWju8o3DXEijiJyn7iqkwktAWq"); _outputs.AddPoolWallet(walletConfig.Adress, blockReward); // job counter _jobCounter = Substitute.For<JobCounter>(); // generation transaction. _generationTransaction = new GenerationTransaction(_extraNonce, _daemonClient, _blockTemplate, _poolConfig); _generationTransaction.Inputs.First().SignatureScript = _signatureScript; _generationTransaction.Outputs = _outputs; _generationTransaction.Create(); // hash algorithm _hashAlgorithm = new Scrypt(); }
public void Init() { _hashAlgorithm = new FNV1aHashAlgorithm(); }
private void SelectFirstAlgo(int index, IHashAlgorithm algo) { lbAlgoSelect.SelectedIndex = index; DisplayCoinsinList(algo); }
public bool ValidateUser(User user, string password) { IHashAlgorithm hashAlgorithm = _hashAlgorithmProvider.GetHashAlgorithm(user.CurrentEncryption); return(CompareByteArrays(user.PasswordHash, hashAlgorithm.GenerateSaltedHash(GetBytes(password), user.PasswordSalt))); }
public IJobManager GetJobManager(IPoolConfig poolConfig, IDaemonClient daemonClient, IJobTracker jobTracker, IShareManager shareManager, IMinerManager minerManager, IHashAlgorithm hashAlgorithm) { var @params = new NamedParameterOverloads { { "poolConfig", poolConfig }, { "daemonClient", daemonClient }, { "jobTracker", jobTracker }, { "shareManager", shareManager }, { "minerManager", minerManager }, { "hashAlgorithm", hashAlgorithm }, }; return(_applicationContext.Container.Resolve <IJobManager>(@params)); }
public override void Init(ZCashBlockTemplate blockTemplate, string jobId, PoolConfig poolConfig, ClusterConfig clusterConfig, IMasterClock clock, IDestination poolAddressDestination, BitcoinNetworkType networkType, bool isPoS, double shareMultiplier, IHashAlgorithm coinbaseHasher, IHashAlgorithm headerHasher, IHashAlgorithm blockHasher) { Contract.RequiresNonNull(blockTemplate, nameof(blockTemplate)); Contract.RequiresNonNull(poolConfig, nameof(poolConfig)); Contract.RequiresNonNull(clusterConfig, nameof(clusterConfig)); Contract.RequiresNonNull(clock, nameof(clock)); Contract.RequiresNonNull(poolAddressDestination, nameof(poolAddressDestination)); Contract.RequiresNonNull(coinbaseHasher, nameof(coinbaseHasher)); Contract.RequiresNonNull(headerHasher, nameof(headerHasher)); Contract.RequiresNonNull(blockHasher, nameof(blockHasher)); Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(jobId), $"{nameof(jobId)} must not be empty"); this.poolConfig = poolConfig; this.clusterConfig = clusterConfig; this.clock = clock; this.poolAddressDestination = poolAddressDestination; this.networkType = networkType; if (ZCashConstants.CoinbaseTxConfig.TryGetValue(poolConfig.Coin.Type, out var coinbaseTx)) { coinbaseTx.TryGetValue(networkType, out coinbaseTxConfig); } BlockTemplate = blockTemplate; JobId = jobId; Difficulty = (double)new BigRational(ZCashConstants.Diff1b, BigInteger.Parse(BlockTemplate.Target, NumberStyles.HexNumber)); this.isPoS = isPoS; this.shareMultiplier = shareMultiplier; this.headerHasher = headerHasher; this.blockHasher = blockHasher; blockTargetValue = BigInteger.Parse(BlockTemplate.Target, NumberStyles.HexNumber); previousBlockHashReversedHex = BlockTemplate.PreviousBlockhash .HexToByteArray() .ReverseArray() .ToHexString(); blockReward = blockTemplate.Subsidy.Miner * BitcoinConstants.SatoshisPerBitcoin; if (coinbaseTxConfig?.PayFoundersReward == true) { var founders = blockTemplate.Subsidy.Founders ?? blockTemplate.Subsidy.Community; if (!founders.HasValue) { throw new Exception("Error, founders reward missing for block template"); } blockReward = (blockTemplate.Subsidy.Miner + founders.Value) * BitcoinConstants.SatoshisPerBitcoin; } rewardFees = blockTemplate.Transactions.Sum(x => x.Fee); BuildCoinbase(); // build tx hashes var txHashes = new List <uint256> { new uint256(coinbaseInitialHash) }; txHashes.AddRange(BlockTemplate.Transactions.Select(tx => new uint256(tx.Hash.HexToByteArray().ReverseArray()))); // build merkle root merkleRoot = MerkleNode.GetRoot(txHashes).Hash.ToBytes().ReverseArray(); merkleRootReversed = merkleRoot.ReverseArray(); merkleRootReversedHex = merkleRootReversed.ToHexString(); jobParams = new object[] { JobId, BlockTemplate.Version.ReverseByteOrder().ToStringHex8(), previousBlockHashReversedHex, merkleRootReversedHex, sha256Empty.ToHexString(), // hashReserved BlockTemplate.CurTime.ReverseByteOrder().ToStringHex8(), BlockTemplate.Bits.HexToByteArray().ReverseArray().ToHexString(), false }; }
public void SetUp() { this.testee = new MD5Algorithm(); }
public IPerPool GetPerPoolStats(IPoolConfig poolConfig, IDaemonClient daemonClient, IMinerManager minerManager, IHashAlgorithm hashAlgorithm, IBlocksCount blockStatistics, IStorage storage) { var @params = new NamedParameterOverloads { { "poolConfig", poolConfig }, { "daemonClient", daemonClient }, { "minerManager", minerManager }, { "hashAlgorithm", hashAlgorithm }, { "blockStatistics", blockStatistics }, { "storage", storage }, }; return(_applicationContext.Container.Resolve <IPerPool>(@params)); }
public DigitalSignature(IHashAlgorithm hash, IAsymmetricCryptoAlgorithm algorithm) { _hashAlgorithm = hash; _algorithm = algorithm; }
public HashAlgorithmAdrSelector(IServiceRouteManager serviceRouteManager, IHealthCheckService healthCheckService, IHashAlgorithm hashAlgorithm) { _healthCheckService = healthCheckService; _hashAlgorithm = hashAlgorithm; //路由发生变更时重建地址条目。 serviceRouteManager.Changed += ServiceRouteManager_Removed; serviceRouteManager.Removed += ServiceRouteManager_Removed; }
public ShareTests() { /* * -- create-generation start -- * rpcData: {"version":2,"previousblockhash":"1c4eb88e47564cb796b5c6648c74bec51d7215ac12fc4168b14827aac74a8062","transactions":[{"data":"010000000332a82e92f522deee69b09e27858ba9b87585f2a4913ef71018df40909032fdc3000000006a473044022019ca05cb880a04f0d842268b7e75ac6d2695fc544df033e3daeb29239251a8970220031f6336767f2ea617347484e1290ec0bdcc71056ea2d3084e75384905250ec50121030dd394118fb66ca288bff71d8ea762678783b005770f7f9ba4128233191e0847ffffffff086747cbd339b21b950774186091653a7b8f5751b00a906ff6f5561b3a6fcee6010000006b4830450221009ae1ba9a216d313cc592fc2c1ef08f1e0e555a32b6c1b305f685ac882d38356b0220243106bbb5bb76dde142e574cba8f30c1e2f7059e8e9161770396fbd2b50420f0121030dd394118fb66ca288bff71d8ea762678783b005770f7f9ba4128233191e0847ffffffffe2f15804b1e41c36c925c6f64f219b2bdb3c9fbff4c97a4f0e8c7f31d7e6f2af000000006b48304502200be8894fdd7f5c19be248a979c08bbf2395f606e038c3e02c0266474c03699ab022100ff5de87086e487410f5d7b68012655ca6d814f0caeb9ca42d9c425a90f68b3030121030dd394118fb66ca288bff71d8ea762678783b005770f7f9ba4128233191e0847ffffffff02a0f01900000000001976a9141c50209a1dfdf53313d237b75e9aeb553ca1dfda88ac00e1f505000000001976a914cbb9a3e7a7c1651b1006f876f08b40be85b274f588ac00000000","hash":"dc3a80ec6c45aa489453b2c4abf6761eb6656d949e26d01793458c166640e5f3","depends":[],"fee":0,"sigops":2}],"coinbaseaux":{"flags":"062f503253482f"},"coinbasevalue":5000000000,"target":"00000048d4f70000000000000000000000000000000000000000000000000000","mintime":1403691059,"mutable":["time","transactions","prevblock"],"noncerange":"00000000ffffffff","sigoplimit":20000,"sizelimit":1000000,"curtime":1403691825,"bits":"1d48d4f7","height":315152} * * -- scriptSigPart data -- * -> height: 315152 serialized: 0310cf04 * -> coinbase: 062f503253482f hex: 062f503253482f * -> date: 1403691824760 final:1403691824 serialized: 0430a3aa53 * -- p1 data -- * txVersion: 1 packed: 01000000 * txInputsCount: 1 varIntBuffer: 01 * txInPrevOutHash: 0 uint256BufferFromHash: 0000000000000000000000000000000000000000000000000000000000000000 * txInPrevOutIndex: 4294967295 packUInt32LE: ffffffff * scriptSigPart1.length: 17 extraNoncePlaceholder.length:8 scriptSigPart2.length:14 all: 39 varIntBuffer: 27 * scriptSigPart1: 0310cf04062f503253482f0430a3aa5308 * p1: 01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff270310cf04062f503253482f0430a3aa5308 * -- generateOutputTransactions -- * block-reward: 5000000000 * recipient-reward: 50000000 packInt64LE: 80f0fa0200000000 * lenght: 25 varIntBuffer: 19 * script: 76a9147d576fbfca48b899dc750167dd2a2a6572fff49588ac * pool-reward: 4950000000 packInt64LE: 80010b2701000000 * lenght: 25 varIntBuffer: 19 * script: 76a914329035234168b8da5af106ceb20560401236849888ac * txOutputBuffers.lenght : 2 varIntBuffer: 02 * -- p2 -- * scriptSigPart2: 0d2f6e6f64655374726174756d2f * txInSequence: 0 packUInt32LE: 00000000 * outputTransactions: 0280010b27010000001976a914329035234168b8da5af106ceb20560401236849888ac80f0fa02000000001976a9147d576fbfca48b899dc750167dd2a2a6572fff49588ac * txLockTime: 0 packUInt32LE: 00000000 * txComment: * p2: 0d2f6e6f64655374726174756d2f000000000280010b27010000001976a914329035234168b8da5af106ceb20560401236849888ac80f0fa02000000001976a9147d576fbfca48b899dc750167dd2a2a6572fff49588ac00000000 * * getJobParams: ["2","c74a8062b14827aa12fc41681d7215ac8c74bec596b5c66447564cb71c4eb88e","01000000010000000000000000000000000000000000000000000000000000000000000000ffffffff270310cf04062f503253482f0430a3aa5308","0d2f6e6f64655374726174756d2f000000000280010b27010000001976a914329035234168b8da5af106ceb20560401236849888ac80f0fa02000000001976a9147d576fbfca48b899dc750167dd2a2a6572fff49588ac00000000",["f3e54066168c459317d0269e946d65b61e76f6abc4b2539448aa456cec803adc"],"00000002","1d48d4f7","53aaa331",true] */ // daemon client _daemonClient = Substitute.For <IDaemonClient>(); _daemonClient.ValidateAddress(Arg.Any <string>()).Returns(new ValidateAddress { IsValid = true }); // block template const string json = "{\"result\":{\"version\":1,\"previousblockhash\":\"1c4eb88e47564cb796b5c6648c74bec51d7215ac12fc4168b14827aac74a8062\",\"transactions\":[{\"data\":\"010000000332a82e92f522deee69b09e27858ba9b87585f2a4913ef71018df40909032fdc3000000006a473044022019ca05cb880a04f0d842268b7e75ac6d2695fc544df033e3daeb29239251a8970220031f6336767f2ea617347484e1290ec0bdcc71056ea2d3084e75384905250ec50121030dd394118fb66ca288bff71d8ea762678783b005770f7f9ba4128233191e0847ffffffff086747cbd339b21b950774186091653a7b8f5751b00a906ff6f5561b3a6fcee6010000006b4830450221009ae1ba9a216d313cc592fc2c1ef08f1e0e555a32b6c1b305f685ac882d38356b0220243106bbb5bb76dde142e574cba8f30c1e2f7059e8e9161770396fbd2b50420f0121030dd394118fb66ca288bff71d8ea762678783b005770f7f9ba4128233191e0847ffffffffe2f15804b1e41c36c925c6f64f219b2bdb3c9fbff4c97a4f0e8c7f31d7e6f2af000000006b48304502200be8894fdd7f5c19be248a979c08bbf2395f606e038c3e02c0266474c03699ab022100ff5de87086e487410f5d7b68012655ca6d814f0caeb9ca42d9c425a90f68b3030121030dd394118fb66ca288bff71d8ea762678783b005770f7f9ba4128233191e0847ffffffff02a0f01900000000001976a9141c50209a1dfdf53313d237b75e9aeb553ca1dfda88ac00e1f505000000001976a914cbb9a3e7a7c1651b1006f876f08b40be85b274f588ac00000000\",\"hash\":\"dc3a80ec6c45aa489453b2c4abf6761eb6656d949e26d01793458c166640e5f3\",\"depends\":[],\"fee\":0,\"sigops\":2}],\"coinbaseaux\":{\"flags\":\"062f503253482f\"},\"coinbasevalue\":5000000000,\"target\":\"00000048d4f70000000000000000000000000000000000000000000000000000\",\"mintime\":1403691059,\"mutable\":[\"time\",\"transactions\",\"prevblock\"],\"noncerange\":\"00000000ffffffff\",\"sigoplimit\":20000,\"sizelimit\":1000000,\"curtime\":1403691825,\"bits\":\"1d48d4f7\",\"height\":315152},\"error\":null,\"id\":1}"; var blockTemplateObject = JsonConvert.DeserializeObject <DaemonResponse <BlockTemplate> >(json); _blockTemplate = blockTemplateObject.Result; // extra nonce _extraNonce = Substitute.For <ExtraNonce>((UInt32)0); // signature script _signatureScript = Substitute.For <SignatureScript>( _blockTemplate.Height, _blockTemplate.CoinBaseAux.Flags, 1403691824760, (byte)_extraNonce.ExtraNoncePlaceholder.Length, "/nodeStratum/"); // pool config var poolConfig = Substitute.For <IPoolConfig>(); // create coin config. var coinConfig = Substitute.For <ICoinConfig>(); coinConfig.Options.TxMessageSupported.Returns(false); coinConfig.Options.IsProofOfStakeHybrid.Returns(false); poolConfig.Coin.Returns(coinConfig); // outputs _outputs = Substitute.For <Outputs>(_daemonClient, coinConfig); double blockReward = 5000000000; // the amount rewarded by the block. // create rewards config. var rewardsConfig = Substitute.For <IRewardsConfig>(); poolConfig.Rewards.Returns(rewardsConfig); var amount = blockReward * 0.01; blockReward -= amount; var rewards = new Dictionary <string, float> { { "mrwhWEDnU6dUtHZJ2oBswTpEdbBHgYiMji", (float)amount } }; rewardsConfig.GetEnumerator().Returns(rewards.GetEnumerator()); foreach (var pair in rewards) { _outputs.AddRecipient(pair.Key, pair.Value); } // create wallet config. var walletConfig = Substitute.For <IWalletConfig>(); poolConfig.Wallet.Returns(walletConfig); // create sample pool central wallet output. walletConfig.Adress.Returns("mk8JqN1kNWju8o3DXEijiJyn7iqkwktAWq"); _outputs.AddPoolWallet(walletConfig.Adress, blockReward); // generation transaction _generationTransaction = Substitute.For <GenerationTransaction>(_extraNonce, _daemonClient, _blockTemplate, poolConfig); _generationTransaction.Inputs.First().SignatureScript = _signatureScript; _generationTransaction.Outputs = _outputs; _generationTransaction.Create(); // hash algorithm _hashAlgorithm = new Scrypt(); // the job. _job = new Job(2, _hashAlgorithm, _blockTemplate, _generationTransaction) { CleanJobs = true }; // the job tracker. _jobTracker = Substitute.For <IJobTracker>(); _jobTracker.Get(2).Returns(_job); // the job manager. _jobManager = Substitute.For <IJobManager>(); _jobManager.ExtraNonce.Next().Returns((UInt32)0x58000000); // coin config _miner = Substitute.For <IStratumMiner>(); _miner.ExtraNonce.Returns((UInt32)0x58000000); }
public Signature(IHashAlgorithm hashAlgorithm, IRollingChecksum rollingChecksumAlgorithm) { HashAlgorithm = hashAlgorithm; RollingChecksumAlgorithm = rollingChecksumAlgorithm; Chunks = new List<ChunkSignature>(); }
public static int GetHashCode( this IHashAlgorithm hashAlgorithm, params int[] hashCodes ) => hashAlgorithm.GetHashCode((IEnumerable <int>)hashCodes);
public CredentialHandler(IHashAlgorithm algorithm, ICacheService cacheService) { timeBasedOneTimePasswordGenerator = new TimeBasedPassword(algorithm, cacheService); }
public ConsistentHash(IHashAlgorithm hashAlgorithm) { _hashAlgorithm = hashAlgorithm; }
public CryptoHashProvider(IFileSystem fileSystem, IHashAlgorithm hashAlgorithm) { _fileSystem = fileSystem; _hashAlgorithm = hashAlgorithm; }
public ConsistentHash(IHashAlgorithm hashAlgorithm, int virtualNodeReplicationFactor) : this(hashAlgorithm) { _virtualNodeReplicationFactor = virtualNodeReplicationFactor; }
public void WriteMetadata(IHashAlgorithm hashAlgorithm, byte[] expectedNewFileHash) { decorated.WriteMetadata(hashAlgorithm, expectedNewFileHash); }
public void Init(BlockTemplate blockTemplate, string jobId, PoolConfig poolConfig, BitcoinPoolConfigExtra extraPoolConfig, ClusterConfig clusterConfig, IMasterClock clock, IDestination poolAddressDestination, Network network, bool isPoS, double shareMultiplier, IHashAlgorithm coinbaseHasher, IHashAlgorithm headerHasher, IHashAlgorithm blockHasher) { Contract.RequiresNonNull(blockTemplate, nameof(blockTemplate)); Contract.RequiresNonNull(poolConfig, nameof(poolConfig)); Contract.RequiresNonNull(clusterConfig, nameof(clusterConfig)); Contract.RequiresNonNull(clock, nameof(clock)); Contract.RequiresNonNull(poolAddressDestination, nameof(poolAddressDestination)); Contract.RequiresNonNull(coinbaseHasher, nameof(coinbaseHasher)); Contract.RequiresNonNull(headerHasher, nameof(headerHasher)); Contract.RequiresNonNull(blockHasher, nameof(blockHasher)); Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(jobId), $"{nameof(jobId)} must not be empty"); this.poolConfig = poolConfig; coin = poolConfig.Template.As <BitcoinTemplate>(); txVersion = coin.CoinbaseTxVersion; this.network = network; this.clock = clock; this.poolAddressDestination = poolAddressDestination; BlockTemplate = blockTemplate; JobId = jobId; Difficulty = new Target(new NBitcoin.BouncyCastle.Math.BigInteger(BlockTemplate.Target, 16)).Difficulty; extraNoncePlaceHolderLength = BitcoinConstants.ExtranoncePlaceHolderLength; this.isPoS = isPoS; this.shareMultiplier = shareMultiplier; txComment = !string.IsNullOrEmpty(extraPoolConfig?.CoinbaseTxComment) ? extraPoolConfig.CoinbaseTxComment : coin.CoinbaseTxComment; if (coin.HasMasterNodes) { masterNodeParameters = BlockTemplate.Extra.SafeExtensionDataAs <MasterNodeBlockTemplateExtra>(); if (!string.IsNullOrEmpty(masterNodeParameters.CoinbasePayload)) { txVersion = 3; var txType = 5; txVersion = txVersion + ((uint)(txType << 16)); } } if (coin.HasPayee) { payeeParameters = BlockTemplate.Extra.SafeExtensionDataAs <PayeeBlockTemplateExtra>(); } this.coinbaseHasher = coinbaseHasher; this.headerHasher = headerHasher; this.blockHasher = blockHasher; if (!string.IsNullOrEmpty(BlockTemplate.Target)) { blockTargetValue = new uint256(BlockTemplate.Target); } else { var tmp = new Target(BlockTemplate.Bits.HexToByteArray()); blockTargetValue = tmp.ToUInt256(); } previousBlockHashReversedHex = BlockTemplate.PreviousBlockhash .HexToByteArray() .ReverseByteOrder() .ToHexString(); BuildMerkleBranches(); BuildCoinbase(); jobParams = new object[] { JobId, previousBlockHashReversedHex, coinbaseInitialHex, coinbaseFinalHex, merkleBranchesHex, BlockTemplate.Version.ToStringHex8(), BlockTemplate.Bits, BlockTemplate.CurTime.ToStringHex8(), false }; }
public Signature(IHashAlgorithm hashAlgorithm, IRollingChecksum rollingChecksumAlgorithm) { HashAlgorithm = hashAlgorithm; RollingChecksumAlgorithm = rollingChecksumAlgorithm; Chunks = new List <ChunkSignature>(); }
public DigestReverser(IHashAlgorithm upstream) { this.upstream = upstream; }
/// <summary> /// Returns a factory instance that creates pre-configured <see cref="TimeBasedPasswordGenerator"/> instances. /// </summary> /// <param name="eraseSecrets">True if the secrets provided to the generated <see cref="TimeBasedPasswordGenerator"/> instances should be overwritten in memory when the generator is disposed.</param> /// <param name="hashAlgorithm">A <see cref="IHashAlgorithm"/> implementation that will be used by the <see cref="TimeBasedPasswordGenerator"/> instances to generate passwords.</param> /// <param name="passwordLength">The number of digits in the generated passwords, default is 6, usual values are 6 or 8.</param> /// <param name="timeInterval">The interval for which each password is valid, the default is 30 seconds.</param> /// <returns>A <see cref="OnetimePasswordGeneratorFactory"/> instance that can be used to create <see cref="TimeBasedPasswordGenerator"/> instances.</returns> /// <seealso cref="TimeBasedPasswordGenerator"/> public static OnetimePasswordGeneratorFactory CreateFactory(bool eraseSecrets, IHashAlgorithm hashAlgorithm, int passwordLength, TimeSpan timeInterval) { return(new OnetimePasswordGeneratorFactory(eraseSecrets, hashAlgorithm, passwordLength, timeInterval)); }
public override void Init(ZCashBlockTemplate blockTemplate, string jobId, PoolConfig poolConfig, ClusterConfig clusterConfig, IMasterClock clock, IDestination poolAddressDestination, BitcoinNetworkType networkType, bool isPoS, double shareMultiplier, decimal blockrewardMultiplier, IHashAlgorithm coinbaseHasher, IHashAlgorithm headerHasher, IHashAlgorithm blockHasher) { Contract.RequiresNonNull(blockTemplate, nameof(blockTemplate)); Contract.RequiresNonNull(poolConfig, nameof(poolConfig)); Contract.RequiresNonNull(clusterConfig, nameof(clusterConfig)); Contract.RequiresNonNull(clock, nameof(clock)); Contract.RequiresNonNull(poolAddressDestination, nameof(poolAddressDestination)); Contract.RequiresNonNull(coinbaseHasher, nameof(coinbaseHasher)); Contract.RequiresNonNull(headerHasher, nameof(headerHasher)); Contract.RequiresNonNull(blockHasher, nameof(blockHasher)); Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(jobId), $"{nameof(jobId)} must not be empty"); this.poolConfig = poolConfig; this.clusterConfig = clusterConfig; this.clock = clock; this.poolAddressDestination = poolAddressDestination; this.networkType = networkType; if (ZCashConstants.Chains.TryGetValue(poolConfig.Coin.Type, out var chain)) { chain.TryGetValue(networkType, out chainConfig); } BlockTemplate = blockTemplate; JobId = jobId; Difficulty = (double)new BigRational(chainConfig.Diff1b, BlockTemplate.Target.HexToByteArray().ReverseArray().ToBigInteger()); txExpiryHeight = blockTemplate.Height + 100; // ZCash Sapling & Overwinter support isSaplingActive = chainConfig.SaplingActivationHeight.HasValue && chainConfig.SaplingTxVersion.HasValue && chainConfig.SaplingTxVersionGroupId.HasValue && chainConfig.SaplingActivationHeight.Value > 0 && blockTemplate.Height >= chainConfig.SaplingActivationHeight.Value; isOverwinterActive = isSaplingActive || chainConfig.OverwinterTxVersion.HasValue && chainConfig.OverwinterTxVersionGroupId.HasValue && chainConfig.OverwinterActivationHeight.HasValue && chainConfig.OverwinterActivationHeight.Value > 0 && blockTemplate.Height >= chainConfig.OverwinterActivationHeight.Value; if (isSaplingActive) { txVersion = chainConfig.SaplingTxVersion.Value; txVersionGroupId = chainConfig.SaplingTxVersionGroupId.Value; } else if (isOverwinterActive) { txVersion = chainConfig.OverwinterTxVersion.Value; txVersionGroupId = chainConfig.OverwinterTxVersionGroupId.Value; } // Misc this.isPoS = isPoS; this.shareMultiplier = shareMultiplier; this.headerHasher = headerHasher; this.blockHasher = blockHasher; this.equihash = chainConfig.Solver(); if (!string.IsNullOrEmpty(BlockTemplate.Target)) { blockTargetValue = new uint256(BlockTemplate.Target); } else { var tmp = new Target(BlockTemplate.Bits.HexToByteArray()); blockTargetValue = tmp.ToUInt256(); } previousBlockHashReversedHex = BlockTemplate.PreviousBlockhash .HexToByteArray() .ReverseArray() .ToHexString(); blockReward = blockTemplate.Subsidy.Miner * BitcoinConstants.SatoshisPerBitcoin; if (chainConfig?.PayFoundersReward == true) { var founders = blockTemplate.Subsidy.Founders ?? blockTemplate.Subsidy.Community; if (!founders.HasValue) { throw new Exception("Error, founders reward missing for block template"); } blockReward = (blockTemplate.Subsidy.Miner + founders.Value) * BitcoinConstants.SatoshisPerBitcoin; } rewardFees = blockTemplate.Transactions.Sum(x => x.Fee); BuildCoinbase(); // build tx hashes var txHashes = new List <uint256> { new uint256(coinbaseInitialHash) }; txHashes.AddRange(BlockTemplate.Transactions.Select(tx => new uint256(tx.Hash.HexToByteArray().ReverseArray()))); // build merkle root merkleRoot = MerkleNode.GetRoot(txHashes).Hash.ToBytes().ReverseArray(); merkleRootReversed = merkleRoot.ReverseArray(); merkleRootReversedHex = merkleRootReversed.ToHexString(); // misc var hashReserved = isSaplingActive && !string.IsNullOrEmpty(blockTemplate.FinalSaplingRootHash) ? blockTemplate.FinalSaplingRootHash.HexToByteArray().ReverseArray().ToHexString() : sha256Empty.ToHexString(); jobParams = new object[] { JobId, BlockTemplate.Version.ReverseByteOrder().ToStringHex8(), previousBlockHashReversedHex, merkleRootReversedHex, hashReserved, BlockTemplate.CurTime.ReverseByteOrder().ToStringHex8(), BlockTemplate.Bits.HexToByteArray().ReverseArray().ToHexString(), false }; }
public SerializerTests() { // daemon client _daemonClient = Substitute.For <IDaemonClient>(); _daemonClient.ValidateAddress(Arg.Any <string>()).Returns(new ValidateAddress { IsValid = true }); // block template const string json = "{\"result\":{\"version\":2,\"previousblockhash\":\"1c4eb88e47564cb796b5c6648c74bec51d7215ac12fc4168b14827aac74a8062\",\"transactions\":[{\"data\":\"010000000332a82e92f522deee69b09e27858ba9b87585f2a4913ef71018df40909032fdc3000000006a473044022019ca05cb880a04f0d842268b7e75ac6d2695fc544df033e3daeb29239251a8970220031f6336767f2ea617347484e1290ec0bdcc71056ea2d3084e75384905250ec50121030dd394118fb66ca288bff71d8ea762678783b005770f7f9ba4128233191e0847ffffffff086747cbd339b21b950774186091653a7b8f5751b00a906ff6f5561b3a6fcee6010000006b4830450221009ae1ba9a216d313cc592fc2c1ef08f1e0e555a32b6c1b305f685ac882d38356b0220243106bbb5bb76dde142e574cba8f30c1e2f7059e8e9161770396fbd2b50420f0121030dd394118fb66ca288bff71d8ea762678783b005770f7f9ba4128233191e0847ffffffffe2f15804b1e41c36c925c6f64f219b2bdb3c9fbff4c97a4f0e8c7f31d7e6f2af000000006b48304502200be8894fdd7f5c19be248a979c08bbf2395f606e038c3e02c0266474c03699ab022100ff5de87086e487410f5d7b68012655ca6d814f0caeb9ca42d9c425a90f68b3030121030dd394118fb66ca288bff71d8ea762678783b005770f7f9ba4128233191e0847ffffffff02a0f01900000000001976a9141c50209a1dfdf53313d237b75e9aeb553ca1dfda88ac00e1f505000000001976a914cbb9a3e7a7c1651b1006f876f08b40be85b274f588ac00000000\",\"hash\":\"dc3a80ec6c45aa489453b2c4abf6761eb6656d949e26d01793458c166640e5f3\",\"depends\":[],\"fee\":0,\"sigops\":2}],\"coinbaseaux\":{\"flags\":\"062f503253482f\"},\"coinbasevalue\":5000000000,\"target\":\"00000048d4f70000000000000000000000000000000000000000000000000000\",\"mintime\":1403691059,\"mutable\":[\"time\",\"transactions\",\"prevblock\"],\"noncerange\":\"00000000ffffffff\",\"sigoplimit\":20000,\"sizelimit\":1000000,\"curtime\":1403691825,\"bits\":\"1d48d4f7\",\"height\":315152},\"error\":null,\"id\":1}"; var @object = JsonConvert.DeserializeObject <DaemonResponse <BlockTemplate> >(json); _blockTemplate = @object.Result; // extra nonce _extraNonce = Substitute.For <ExtraNonce>((UInt32)0); // signature script _signatureScript = Substitute.For <SignatureScript>( _blockTemplate.Height, _blockTemplate.CoinBaseAux.Flags, 1403691824760, (byte)_extraNonce.ExtraNoncePlaceholder.Length, "/nodeStratum/"); // outputs _outputs = Substitute.For <Outputs>(_daemonClient); double blockReward = 5000000000; // the amount rewarded by the block. // sample reward recipient var rewardsConfig = Substitute.For <IRewardsConfig>(); var amount = blockReward * 0.01; blockReward -= amount; var rewards = new Dictionary <string, float> { { "mrwhWEDnU6dUtHZJ2oBswTpEdbBHgYiMji", (float)amount } }; rewardsConfig.GetEnumerator().Returns(rewards.GetEnumerator()); foreach (var pair in rewards) { _outputs.AddRecipient(pair.Key, pair.Value); } // sample pool wallet var walletConfig = Substitute.For <IWalletConfig>(); walletConfig.Adress.Returns("mk8JqN1kNWju8o3DXEijiJyn7iqkwktAWq"); _outputs.AddPoolWallet(walletConfig.Adress, blockReward); var metaConfig = Substitute.For <IMetaConfig>(); // generation transaction. _generationTransaction = Substitute.For <GenerationTransaction>(_extraNonce, _daemonClient, _blockTemplate, walletConfig, rewardsConfig, metaConfig, false); //_generationTransaction.Inputs.First().SignatureScript = _signatureScript; //_generationTransaction.Outputs = _outputs; _generationTransaction.Create(); // job counter _jobCounter = Substitute.For <IJobCounter>(); _jobCounter.Next().Returns((UInt64)2); // hash algorithm _hashAlgorithm = Substitute.For <IHashAlgorithm>(); // create the job _job = Substitute.For <Job>(_jobCounter.Next(), _hashAlgorithm, _blockTemplate, _generationTransaction); }
public Electroneum(IHashAlgorithm algo) { Algorithm = algo; //This is only used in Debug mode for quick testing of the miner DefaultAddress = "etnjzKFU6ogESSKRZZbdqraPdcKVxEC17Cm1Xvbyy76PARQMmgrgceH4krAH6xmjKwJ3HtSAKuyFm1BBWYqtchtq9tBap8Qr4M"; }
public BitcoinCoinProperties(double shareMultiplier, IHashAlgorithm coinbaseHasher, IHashAlgorithm headerHasher, IHashAlgorithm blockHasher, IHashAlgorithm posblockHasher = null) { ShareMultiplier = shareMultiplier; CoinbaseHasher = coinbaseHasher; HeaderHasher = headerHasher; BlockHasher = blockHasher; PoSBlockHasher = posblockHasher; }
public CrytpoHashProvider(IFileSystem fileSystem, IHashAlgorithm hashAlgorithm) { _fileSystem = fileSystem; _hashAlgorithm = hashAlgorithm; }
public virtual void Init(TBlockTemplate blockTemplate, string jobId, PoolConfig poolConfig, ClusterConfig clusterConfig, IMasterClock clock, IDestination poolAddressDestination, BitcoinNetworkType networkType, bool isPoS, double shareMultiplier, decimal blockrewardMultiplier, IHashAlgorithm coinbaseHasher, IHashAlgorithm headerHasher, IHashAlgorithm blockHasher) { Contract.RequiresNonNull(blockTemplate, nameof(blockTemplate)); Contract.RequiresNonNull(poolConfig, nameof(poolConfig)); Contract.RequiresNonNull(clusterConfig, nameof(clusterConfig)); Contract.RequiresNonNull(clock, nameof(clock)); Contract.RequiresNonNull(poolAddressDestination, nameof(poolAddressDestination)); Contract.RequiresNonNull(coinbaseHasher, nameof(coinbaseHasher)); Contract.RequiresNonNull(headerHasher, nameof(headerHasher)); Contract.RequiresNonNull(blockHasher, nameof(blockHasher)); Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(jobId), $"{nameof(jobId)} must not be empty"); this.poolConfig = poolConfig; this.clusterConfig = clusterConfig; this.clock = clock; this.poolAddressDestination = poolAddressDestination; this.networkType = networkType; BlockTemplate = blockTemplate; JobId = jobId; Difficulty = new Target(new NBitcoin.BouncyCastle.Math.BigInteger(BlockTemplate.Target, 16)).Difficulty; extraNoncePlaceHolderLength = BitcoinConstants.ExtranoncePlaceHolderLength; this.isPoS = isPoS; this.shareMultiplier = shareMultiplier; this.blockRewardMultiplier = blockrewardMultiplier; this.coinbaseHasher = coinbaseHasher; this.headerHasher = headerHasher; this.blockHasher = blockHasher; if (!string.IsNullOrEmpty(BlockTemplate.Target)) { blockTargetValue = new uint256(BlockTemplate.Target); } else { var tmp = new Target(BlockTemplate.Bits.HexToByteArray()); blockTargetValue = tmp.ToUInt256(); } previousBlockHashReversedHex = BlockTemplate.PreviousBlockhash .HexToByteArray() .ReverseByteOrder() .ToHexString(); BuildMerkleBranches(); BuildCoinbase(); jobParams = new object[] { JobId, previousBlockHashReversedHex, coinbaseInitialHex, coinbaseFinalHex, merkleBranchesHex, BlockTemplate.Version.ToStringHex8(), BlockTemplate.Bits, BlockTemplate.CurTime.ToStringHex8(), false }; }
public SerializerTests() { // daemon client _daemonClient = Substitute.For<IDaemonClient>(); _daemonClient.ValidateAddress(Arg.Any<string>()).Returns(new ValidateAddress { IsValid = true }); // block template const string json = "{\"result\":{\"version\":2,\"previousblockhash\":\"1c4eb88e47564cb796b5c6648c74bec51d7215ac12fc4168b14827aac74a8062\",\"transactions\":[{\"data\":\"010000000332a82e92f522deee69b09e27858ba9b87585f2a4913ef71018df40909032fdc3000000006a473044022019ca05cb880a04f0d842268b7e75ac6d2695fc544df033e3daeb29239251a8970220031f6336767f2ea617347484e1290ec0bdcc71056ea2d3084e75384905250ec50121030dd394118fb66ca288bff71d8ea762678783b005770f7f9ba4128233191e0847ffffffff086747cbd339b21b950774186091653a7b8f5751b00a906ff6f5561b3a6fcee6010000006b4830450221009ae1ba9a216d313cc592fc2c1ef08f1e0e555a32b6c1b305f685ac882d38356b0220243106bbb5bb76dde142e574cba8f30c1e2f7059e8e9161770396fbd2b50420f0121030dd394118fb66ca288bff71d8ea762678783b005770f7f9ba4128233191e0847ffffffffe2f15804b1e41c36c925c6f64f219b2bdb3c9fbff4c97a4f0e8c7f31d7e6f2af000000006b48304502200be8894fdd7f5c19be248a979c08bbf2395f606e038c3e02c0266474c03699ab022100ff5de87086e487410f5d7b68012655ca6d814f0caeb9ca42d9c425a90f68b3030121030dd394118fb66ca288bff71d8ea762678783b005770f7f9ba4128233191e0847ffffffff02a0f01900000000001976a9141c50209a1dfdf53313d237b75e9aeb553ca1dfda88ac00e1f505000000001976a914cbb9a3e7a7c1651b1006f876f08b40be85b274f588ac00000000\",\"hash\":\"dc3a80ec6c45aa489453b2c4abf6761eb6656d949e26d01793458c166640e5f3\",\"depends\":[],\"fee\":0,\"sigops\":2}],\"coinbaseaux\":{\"flags\":\"062f503253482f\"},\"coinbasevalue\":5000000000,\"target\":\"00000048d4f70000000000000000000000000000000000000000000000000000\",\"mintime\":1403691059,\"mutable\":[\"time\",\"transactions\",\"prevblock\"],\"noncerange\":\"00000000ffffffff\",\"sigoplimit\":20000,\"sizelimit\":1000000,\"curtime\":1403691825,\"bits\":\"1d48d4f7\",\"height\":315152},\"error\":null,\"id\":1}"; var @object = JsonConvert.DeserializeObject<DaemonResponse<BlockTemplate>>(json); _blockTemplate = @object.Result; // extra nonce _extraNonce = Substitute.For<ExtraNonce>((UInt32)0); // signature script _signatureScript = Substitute.For<SignatureScript>( _blockTemplate.Height, _blockTemplate.CoinBaseAux.Flags, 1403691824760, (byte)_extraNonce.ExtraNoncePlaceholder.Length, "/nodeStratum/"); // outputs _outputs = Substitute.For<Outputs>(_daemonClient); double blockReward = 5000000000; // the amount rewarded by the block. // sample reward recipient var rewardsConfig = Substitute.For<IRewardsConfig>(); var amount = blockReward * 0.01; blockReward -= amount; var rewards = new Dictionary<string, float> { { "mrwhWEDnU6dUtHZJ2oBswTpEdbBHgYiMji", (float)amount } }; rewardsConfig.GetEnumerator().Returns(rewards.GetEnumerator()); foreach (var pair in rewards) { _outputs.AddRecipient(pair.Key, pair.Value); } // sample pool wallet var walletConfig = Substitute.For<IWalletConfig>(); walletConfig.Adress.Returns("mk8JqN1kNWju8o3DXEijiJyn7iqkwktAWq"); _outputs.AddPoolWallet(walletConfig.Adress, blockReward); // generation transaction. _generationTransaction = Substitute.For<GenerationTransaction>(_extraNonce, _daemonClient, _blockTemplate, walletConfig, rewardsConfig, false); _generationTransaction.Inputs.First().SignatureScript = _signatureScript; _generationTransaction.Outputs = _outputs; _generationTransaction.Create(); // job counter _jobCounter = Substitute.For<IJobCounter>(); _jobCounter.Next().Returns((UInt64)2); // hash algorithm _hashAlgorithm = Substitute.For<IHashAlgorithm>(); // create the job _job = Substitute.For<Job>(_jobCounter.Next(), _hashAlgorithm, _blockTemplate, _generationTransaction); }
public void set_hash_algorithm(CryptoHashProviderType algorithmType) { _hashAlgorithm = get_hash_algorithm_static(algorithmType); }
public override void Init(ZCashBlockTemplate blockTemplate, string jobId, PoolConfig poolConfig, ClusterConfig clusterConfig, IMasterClock clock, IDestination poolAddressDestination, BitcoinNetworkType networkType, bool isPoS, double shareMultiplier, IHashAlgorithm coinbaseHasher, IHashAlgorithm headerHasher, IHashAlgorithm blockHasher) { Contract.RequiresNonNull(blockTemplate, nameof(blockTemplate)); Contract.RequiresNonNull(poolConfig, nameof(poolConfig)); Contract.RequiresNonNull(clusterConfig, nameof(clusterConfig)); Contract.RequiresNonNull(clock, nameof(clock)); Contract.RequiresNonNull(poolAddressDestination, nameof(poolAddressDestination)); Contract.RequiresNonNull(coinbaseHasher, nameof(coinbaseHasher)); Contract.RequiresNonNull(headerHasher, nameof(headerHasher)); Contract.RequiresNonNull(blockHasher, nameof(blockHasher)); Contract.Requires <ArgumentException>(!string.IsNullOrEmpty(jobId), $"{nameof(jobId)} must not be empty"); this.poolConfig = poolConfig; this.clusterConfig = clusterConfig; this.clock = clock; this.poolAddressDestination = poolAddressDestination; this.networkType = networkType; BlockTemplate = blockTemplate; JobId = jobId; Difficulty = (double)new BigRational(ZCashConstants.Diff1b, BlockTemplate.Target.HexToByteArray().ToBigInteger()); this.isPoS = isPoS; this.shareMultiplier = shareMultiplier; this.headerHasher = headerHasher; this.blockHasher = blockHasher; if (!string.IsNullOrEmpty(BlockTemplate.Target)) { blockTargetValue = new uint256(BlockTemplate.Target); } else { var tmp = new Target(BlockTemplate.Bits.HexToByteArray()); blockTargetValue = tmp.ToUInt256(); } previousBlockHashReversedHex = BlockTemplate.PreviousBlockhash .HexToByteArray() .ReverseArray() .ToHexString(); BuildCoinbase(); // build tx hashes var txHashes = new List <uint256> { new uint256(coinbaseInitialHash) }; txHashes.AddRange(BlockTemplate.Transactions.Select(tx => new uint256(tx.TxId.HexToByteArray().ReverseArray()))); // build merkle root merkleRoot = MerkleNode.GetRoot(txHashes).Hash.ToBytes().ReverseArray(); merkleRootReversed = merkleRoot.ReverseArray(); merkleRootReversedHex = merkleRootReversed.ToHexString(); jobParams = new object[] { JobId, BlockTemplate.Version.ReverseByteOrder().ToStringHex8(), previousBlockHashReversedHex, merkleRootReversedHex, BlockTemplate.Height.ReverseByteOrder().ToStringHex8() + sha256Empty.Take(28).ToHexString(), // height + hashReserved BlockTemplate.CurTime.ReverseByteOrder().ToStringHex8(), BlockTemplate.Bits.HexToByteArray().ReverseArray().ToHexString(), false }; }
public void WriteMetadata(IHashAlgorithm hashAlgorithm, byte[] expectedNewFileHash, long filesize, short chunkSize) { decorated.WriteMetadata(hashAlgorithm, expectedNewFileHash, filesize, chunkSize); }
/// <summary> /// The initialize. /// </summary> /// <exception cref="Exception"> /// </exception> public void Initialize() { try { var asm = Assembly.GetExecutingAssembly(); hashAlgorithm = new HashAlgorithm(); // Конфиг var configXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<configuration>" + "<keys>" + "<key name=\"H11{Doc}\" type=\"111\" value=\"FamilyName + FirstName + MiddleName + BirthPlace + RealIdentifier\"/>" + "<key name=\"H12{Doc}\" type=\"121\" value=\"FamilyName + FirstName + MiddleName + BirthDate + RealIdentifier\"/>" + "<key name=\"H14{Pol}\" type=\"141\" value=\"FamilyName + FirstName + MiddleName + BirthDate + PolicyNumber\"/>" + "<key name=\"H15.PEN\" type=\"151\" value=\"FirstName + MiddleName + BirthPlace + SNILS\"/>" + "<key name=\"H16.PEN\" type=\"161\" value=\"FirstName + MiddleName + BirthDate + SNILS\"/>" + "<key name=\"H17\" type=\"171\" subtype=\"0\" value=\"FamilyName + FirstName + MiddleName + BirthPlace\"/>" + "<key name=\"H18\" type=\"181\" subtype=\"0\" value=\"FamilyName + FirstName + MiddleName + BirthDate\"/>" + "<oldkey name=\"H01\" type=\"51\"/>" + "<oldkey name=\"H02\" type=\"11\"/>" + "<oldkey name=\"H03\" type=\"21\"/>" + "<oldkey name=\"H04\" type=\"31\"/>" + "<oldkey name=\"H05\" type=\"41\"/>" + "</keys>" + "<subtypes>" + "<subtype name=\"NI\" value=\"19\"/>" + "<subtype name=\"PEN\" value=\"20\"/>" + "<subtype name=\"CZ\" value=\"25\"/>" + "<subtype name=\"С\" value=\"101\"/>" + "<subtype name=\"В\" value=\"105\"/>" + "<subtype name=\"П\" value=\"111\"/>" + "<subtype name=\"Э\" value=\"112\"/>" + "<subtype name=\"К\" value=\"113\"/>" + "</subtypes>" + "</configuration>"; using (var stream = new MemoryStream()) { var writer = new StreamWriter(stream); writer.Write(configXml); writer.Flush(); stream.Position = 0; loadedKeys = KeysLoader.LoadKeys(stream, out subtypes, ResolveFields); } var textRulesXml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Правила>" + "<Текстовые ВерхнийРегистр=\"Да\" СхлопнутьПробелы=\"Да\" УбратьБоковыеПробелы=\"Да\">" + "<Заменить Символы=\"–—?\" На=\"-\" />" + "<Заменить Символы=\"A\" На=\"А\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" />" + "<Заменить Символы=\"B\" На=\"В\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" />" + "<Заменить Символы=\"C\" На=\"С\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" />" + "<Заменить Символы=\"E\" На=\"Е\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" />" + "<Заменить Символы=\"H\" На=\"Н\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" />" + "<Заменить Символы=\"K\" На=\"К\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" />" + "<Заменить Символы=\"M\" На=\"М\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" />" + "<Заменить Символы=\"O\" На=\"О\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" />" + "<Заменить Символы=\"P\" На=\"Р\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" />" + "<Заменить Символы=\"T\" На=\"Т\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" />" + "<Заменить Символы=\"X\" На=\"Х\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" />" + "<Заменить Символы=\"Ё\" На=\"Е\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" />" + "<Заменить Коды=\"9,10,12,13,160\" На=\" \" ТолькоПоля=\"BirthPlace\" />" + "<Заменить Символы=\"_\" На=\" \" ТолькоПоля=\"BirthPlace\" />" + "<Заменить Коды=\"34,60,62\" На=\"'\" ТолькоПоля=\"BirthPlace\" />" + "<Заменить Символы=\"`„‹‘’“”›«»\" На=\"'\" ТолькоПоля=\"BirthPlace\" />" + "<Заменить Символы=\"[{\" На=\"(\" ТолькоПоля=\"BirthPlace\" />" + "<Заменить Символы=\"]}\" На=\")\" ТолькоПоля=\"BirthPlace\" />" + "<Заменить Символы=\"\\|¦\" На=\"/\" ТолькоПоля=\"BirthPlace\" />" + "<Заменить Символы=\"‚\" На=\",\" ТолькоПоля=\"BirthPlace\" />" + "<Заменить Символы=\"…\" На=\".\" ТолькоПоля=\"BirthPlace\" />" + "<Заменить Символы=\"•\" На=\".\" ТолькоПоля=\"BirthPlace\" />" + "<Заменить Символы=\"№\" На=\"N\" ТолькоПоля=\"BirthPlace\" />" + "<Заменить Сочетание=\"V\" На=\"У\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" ТолькоНестрогий=\"Да\" />" + "<Заменить Сочетание=\"D\" На=\"Д\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" ТолькоНестрогий=\"Да\" />" + "<Заменить Сочетание=\"L\" На=\"Л\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" ТолькоНестрогий=\"Да\" />" + "<Заменить Сочетание=\"111\" На=\"Ш\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" ТолькоНестрогий=\"Да\" />" + "<Заменить Сочетание=\"11\" На=\"П\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" ТолькоНестрогий=\"Да\" />" + "<Заменить Сочетание=\"III\" На=\"Ш\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" ТолькоНестрогий=\"Да\" />" + "<Заменить Сочетание=\"II\" На=\"П\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" ТолькоНестрогий=\"Да\" />" + "<Заменить Сочетание=\"I\" На=\"1\" ТолькоПоля=\"FamilyName, FirstName, MiddleName, BirthPlace\" ТолькоНестрогий=\"Да\" />" + "<УбратьПробелы Слева=\"Да\" Справа=\"Да\" Символы=\"-.'\" ТолькоПоля=\"FamilyName, FirstName, MiddleName\" />" + "<УбратьПробелы Слева=\"Да\" Справа=\"Да\" Символы=\"-.,\" ТолькоПоля=\"BirthPlace\" />" + "</Текстовые>" + "</Правила>"; var xmlReader = new XmlTextReader(new StringReader(textRulesXml)); textRules = new TextRules(XElement.Load(xmlReader), ResolveFields); // var name = string.Format("{0}.{1}", asm.GetName().Name, formats); // var stm = asm.GetManifestResourceStream(name); // assumptions = new Assumptions(); // assumptions.LoadAssumptions(XElement.Load(XmlReader.Create(stm)), clearExistingRules: false); } catch (Exception ex) { throw new Exception("Ошибка при инициализации: ", ex); } }
public DuplicateService(IHashAlgorithm hashAlgorithm, Configuration configuration) { _hashAlgorithm = hashAlgorithm; _configuration = configuration; }