@ -5,25 +5,21 @@ private extension UInt64 {
init ( _ decimal : Decimal ) {
self . init ( truncating : decimal as NSDecimalNumber )
}
// C o n v e r t a U I n t 8 a r r a y t o a U I n t 6 4
init ( _ bytes : [ UInt8 ] ) {
precondition ( bytes . count <= MemoryLayout < UInt64 > . size )
var value : UInt64 = 0
for byte in bytes {
value <<= 8
value |= UInt64 ( byte )
}
self . init ( value )
}
}
// U I n t 8 A r r a y s p e c i f i c s t u f f w e n e e d
private extension Array where Element = = UInt8 {
// C o n v e r t a U I n t 6 4 i n t o a n a r r a y o f s i z e 8
init ( _ uint64 : UInt64 ) {
let array = stride ( from : 0 , to : 64 , by : 8 ) . reversed ( ) . map {
UInt8 ( uint64 >> $0 & 0x000000FF )
}
self . init ( array )
}
static func > ( lhs : [ UInt8 ] , rhs : [ UInt8 ] ) -> Bool {
guard lhs . count = = rhs . count else { return false }
guard let ( lhsElement , rhsElement ) = zip ( lhs , rhs ) . first ( where : { $0 != $1 } ) else { return false }
return lhsElement > rhsElement
}
// / I n c r e m e n t t h e U I n t 8 a r r a y b y a g i v e n a m o u n t
// /
// / - P a r a m e t e r a m o u n t : T h e a m o u n t t o i n c r e m e n t b y
@ -91,8 +87,8 @@ public enum ProofOfWork {
let payload = config . payload
let target = calcTarget ( ttl : config . ttl , payloadLength : payload . count , nonceTrials : nonceTrialCount )
// S t a r t w i t h mo s t th e m a x v a l u e w e c a n
var trialValue = [ UInt8 ] ( repeating : UInt8 . max , count : nonceLength )
// S t a r t w i t h th e m a x v a l u e
var trialValue = UInt64 . max
let initialHash = payload . sha512 ( )
var nonce = [ UInt8 ] ( repeating : 0 , count : nonceLength )
@ -103,14 +99,15 @@ public enum ProofOfWork {
// T h i s i s d i f f e r e n t t o t h e b i t m e s s a g e p o w
// r e s u l t H a s h = h a s h ( n o n c e + h a s h ( d a t a ) ) = = > h a s h ( n o n c e + i n i t i a l H a s h )
let resultHash = ( nonce + initialHash ) . sha512 ( )
trialValue = Array ( resultHash [ 0. . < 8 ] )
let trialValueArray = Array ( resultHash [ 0. . < 8 ] )
trialValue = UInt64 ( trialValueArray )
}
return nonce . toBase64 ( )
}
// / C a l c u l a t e t h e U I n t 8 t a r g e t w e n e e d t o r e a c h
private static func calcTarget ( ttl : Int , payloadLength : Int , nonceTrials : Int ) -> [ UInt8 ] {
private static func calcTarget ( ttl : Int , payloadLength : Int , nonceTrials : Int ) -> UInt64 {
let two16 = UInt64 ( pow ( 2 , 16 ) - 1 )
let two64 = UInt64 ( pow ( 2 , 64 ) - 1 )
@ -125,8 +122,7 @@ public enum ProofOfWork {
let innerFrac = ttlMult / two16
let lenPlusInnerFrac = totalLength + innerFrac
let denominator = UInt64 ( nonceTrials ) * lenPlusInnerFrac
let targetNum = two64 / denominator
return [ UInt8 ] ( targetNum )
return two64 / denominator
}
}