Guest User

Untitled

a guest
Jan 21st, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. @_exported import Vapor
  2. import Foundation
  3.  
  4. //Global client state
  5. let state = State()
  6.  
  7.  
  8. extension Droplet {
  9. public func setup() throws {
  10. try setupRoutes()
  11.  
  12. //For now init state by reading value from there.
  13. print("BlockChain count: \(state.blockChain.count)")
  14. self.mine()
  15.  
  16. }
  17.  
  18.  
  19. func mine(){
  20.  
  21. let miner = Miner(coinbase: "asdf", diff: 5000, threadCount: 4)
  22. let block = Block(prevHash: state.getPreviousBlock().blockHash, depth: state.blockChain.count, txns: [Transaction()], timestamp: Date().timeIntervalSince1970, difficulty: 5000, nonce: 0, hash: Data())
  23.  
  24. block.nonce = 0
  25. block.blockHash = block.encoded().sha256
  26.  
  27. let queue = state.miningQueue
  28. queue.cancelAllOperations()
  29. queue.isSuspended = true
  30. queue.maxConcurrentOperationCount = miner.threadCount
  31. print("BEGIN - queue:",queue.operationCount)
  32. for idx in 0...miner.threadCount-1{
  33. let op = Operation()
  34. op.completionBlock = {
  35. let candidate = block.newCopy()
  36.  
  37. //Start each thread with a nonce at different spot
  38. candidate.nonce = UInt64(idx) * (UINT64_MAX/UInt64(miner.threadCount))
  39.  
  40. //TODO: Find a more efficient way to check prefix zeroes.
  41. while (!candidate.blockHash.binaryString.hasPrefix("0000")) {
  42. candidate.nonce += 1
  43. candidate.timestamp = Date().timeIntervalSince1970
  44. candidate.blockHash = candidate.encoded().sha256
  45. if op.isCancelled {
  46. break
  47. }
  48.  
  49. }
  50. if op.isCancelled {
  51. return
  52. }else{
  53. queue.isSuspended = true
  54. queue.cancelAllOperations()
  55. sleep(1)
  56. print(">>> queue:",queue.operationCount)
  57. self.mine()
  58. }
  59. }
  60. queue.addOperation(op)
  61. }
  62.  
  63. print("END - queue:",queue.operationCount)
  64. queue.isSuspended = false
  65.  
  66.  
  67.  
  68.  
  69. }
  70.  
  71. }
Add Comment
Please, Sign In to add comment