Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @_exported import Vapor
- import Foundation
- //Global client state
- let state = State()
- extension Droplet {
- public func setup() throws {
- try setupRoutes()
- //For now init state by reading value from there.
- print("BlockChain count: \(state.blockChain.count)")
- self.mine()
- }
- func mine(){
- let miner = Miner(coinbase: "asdf", diff: 5000, threadCount: 4)
- let block = Block(prevHash: state.getPreviousBlock().blockHash, depth: state.blockChain.count, txns: [Transaction()], timestamp: Date().timeIntervalSince1970, difficulty: 5000, nonce: 0, hash: Data())
- block.nonce = 0
- block.blockHash = block.encoded().sha256
- let queue = state.miningQueue
- queue.cancelAllOperations()
- queue.isSuspended = true
- queue.maxConcurrentOperationCount = miner.threadCount
- print("BEGIN - queue:",queue.operationCount)
- for idx in 0...miner.threadCount-1{
- let op = Operation()
- op.completionBlock = {
- let candidate = block.newCopy()
- //Start each thread with a nonce at different spot
- candidate.nonce = UInt64(idx) * (UINT64_MAX/UInt64(miner.threadCount))
- //TODO: Find a more efficient way to check prefix zeroes.
- while (!candidate.blockHash.binaryString.hasPrefix("0000")) {
- candidate.nonce += 1
- candidate.timestamp = Date().timeIntervalSince1970
- candidate.blockHash = candidate.encoded().sha256
- if op.isCancelled {
- break
- }
- }
- if op.isCancelled {
- return
- }else{
- queue.isSuspended = true
- queue.cancelAllOperations()
- sleep(1)
- print(">>> queue:",queue.operationCount)
- self.mine()
- }
- }
- queue.addOperation(op)
- }
- print("END - queue:",queue.operationCount)
- queue.isSuspended = false
- }
- }
Add Comment
Please, Sign In to add comment