Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify #153 #170

Merged
merged 8 commits into from
Sep 12, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 48 additions & 8 deletions BitcoinKit.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
codeCoverageEnabled = "YES"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
Expand Down
37 changes: 37 additions & 0 deletions Sources/BitcoinKit/Core/Math.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//
// Math.swift
//
// Copyright © 2018 BitcoinKit developers
///
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
///

import Foundation

func ceil_log2(_ x: UInt32) -> UInt32 {
if x == 0 { return 0 }
guard x > 1 else { return 0 }
var xx: UInt32 = x - 1
var r: UInt32 = 0
while xx > 0 {
xx >>= 1
r += 1
}
return r
}
95 changes: 95 additions & 0 deletions Sources/BitcoinKit/Core/MerkleTree.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
//
// MerkleTree.swift
//
// Copyright © 2018 BitcoinKit developers
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

import Foundation

struct MerkleTree {
enum MerkleError: Error {
case noEnoughParent
case noEnoughHash
case duplicateHash // CVE-2012-2459
case invalidNumberOfHashes
case invalidNumberOfFlags
case nullHash
}

static func buildMerkleRoot(numberOfHashes: UInt32, hashes: [Data], numberOfFlags: UInt32, flags: [UInt8], totalTransactions: UInt32) throws -> Data {
if numberOfHashes != hashes.count {
throw MerkleError.invalidNumberOfHashes
}
if flags.count < numberOfFlags / 8 {
throw MerkleError.invalidNumberOfFlags
}
let parents: [Bool] = (0 ..< Int(numberOfFlags)).compactMap({
return (flags[$0 / 8] & UInt8(1 << ($0 % 8))) != 0
})
let maxdepth: UInt = UInt(ceil_log2(totalTransactions))
var hashIterator = hashes.makeIterator()
var parentIterator = parents.makeIterator()
let root = try buildPartialMerkleTree(hashIterator: &hashIterator, parentIterator: &parentIterator, depth: 0, maxdepth: maxdepth)
guard let h = root.hash else { throw MerkleError.nullHash }
return h
}

struct PartialMerkleTree {
var hash: Data?
// zero size if depth is maxdepth
// leaf[0]: left, leaf[1]: right
var leaf: [PartialMerkleTree] = []
init(hash: Data, leafL: PartialMerkleTree, leafR: PartialMerkleTree) {
self.hash = hash
leaf.append(leafL)
leaf.append(leafR)
}
init(hash: Data) {
self.hash = hash
}
}

private static func buildPartialMerkleTree(
hashIterator: inout IndexingIterator<[Data]>,
parentIterator: inout IndexingIterator<[Bool]>,
depth: UInt, maxdepth: UInt) throws -> PartialMerkleTree {
guard let parent = parentIterator.next() else { throw MerkleError.noEnoughParent }
if !parent || maxdepth <= depth {
// leaf
guard let hash = hashIterator.next() else { throw MerkleError.noEnoughHash }
return PartialMerkleTree(hash: hash)
} else {
// vertex
let left: PartialMerkleTree = try buildPartialMerkleTree(hashIterator: &hashIterator, parentIterator: &parentIterator, depth: depth + 1, maxdepth: maxdepth)
let right: PartialMerkleTree = try buildPartialMerkleTree(hashIterator: &hashIterator, parentIterator: &parentIterator, depth: depth + 1, maxdepth: maxdepth)
if let h0 = left.hash, let h1 = right.hash {
if h0 == h1 {
// CVE-2012-2459
throw MerkleError.duplicateHash
}
let hash = Crypto.sha256sha256(h0 + h1)
return PartialMerkleTree(hash: hash, leafL: left, leafR: right)
} else {
throw MerkleError.nullHash
}
}
}
}
56 changes: 56 additions & 0 deletions Sources/BitcoinKit/Core/ProofOfWork.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
//
// ProofOfWork.swift
//
// Copyright © 2018 BitcoinKit developers
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

import Foundation

class ProofOfWork {
static let maxProofOfWork: UInt256
= UInt256(data: Data(hex: "00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff")!)!
static func isValidProofOfWork(blockHash: Data, bits: UInt32) -> Bool {
let target: UInt256
do {
target = try UInt256(compact: bits)
} catch {
// invalid bits
return false
}
guard target != UInt256.zero else {
// invalid zero target
return false
}
guard target <= maxProofOfWork else {
// too high target
return false
}
guard let arith_hash = UInt256(data: blockHash) else {
// invalid blockHash data length
return false
}
guard arith_hash <= target else {
// insufficient proof of work
return false
}
return true
}
}
52 changes: 52 additions & 0 deletions Sources/BitcoinKit/Core/UInt256+Bitcoin.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
//
// UInt256+Bitcoin.swift
//
// Copyright © 2018 BitcoinKit developers
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

import Foundation

extension UInt256 {
public enum CompactError: Error {
case negative, overflow
}
// bitcoin "compact" format
public init(compact: UInt32) throws {
let size: UInt32 = compact >> 24
let target: UInt32 = compact & 0x007fffff
if target == 0 {
self = UInt256.zero
} else {
// The 0x00800000 denotes the sign
if (compact & 0x00800000) != 0 {
throw CompactError.negative
}
if size > 0x22 || (target > 0xff && size > 0x21) || (target > 0xffff && size > 0x20) {
throw CompactError.overflow
}
if size < 3 {
self = UInt256(target) >> ((3 - size) * 8)
} else {
self = UInt256(target) << ((size - 3) * 8)
}
}
}
}
Loading