oleganza / corebitcoin Goto Github PK
View Code? Open in Web Editor NEWAwesome Bitcoin toolkit for ObjC and Swift
License: Do What The F*ck You Want To Public License
Awesome Bitcoin toolkit for ObjC and Swift
License: Do What The F*ck You Want To Public License
Just adding this here to track this feature.
Hi,
I have question about generate public key using Swift. I need to generate random public keys to check transactions in wallets, is this possible? Can You give me some tips how to do this?
Tag needs to be added for 0.6.2 to match what's in the podspec. Thanks =)
Currently BTCBlock
and BTCBlockHeader
are only good to compose and hold data received from 3rd parties (e.g. Chain-iOS SDK), but cannot parse raw serialized data.
BTCPaymentProtocol
currently uses API SecKeyRawVerify
only available on iOS, but not on OS X. To support signature verification on OS X, we need to use SecVerifyTransformCreate
("Security Transforms" API). There's already some draft code in comments as a starting point.
Add support for ECIES like in Bitcore-ECIES.
Bounty of 3 BTC placed by @yrashk.
In version 1.0.1.16
of OpenSSL-Universal (on which CoreBitcoin depends) -miphoneos-version-min
was left out when compiling resulting in hundreds of linker warnings when compiling for an iOS version lower than 9.2.
The warnings look like this:
ld: warning: object file (/Users/rick/projects/bitx/ios/app/Pods/OpenSSL-Universal/lib-ios/libcrypto.a(cryptlib.o)) was built for newer iOS version (9.2) than being linked (8.0)
This was fixed in version 1.0.1.17
of OpenSSL-Universal, so updating the dependency to that version or newer will fix the issue.
Can CoreBitcoin please make that update?
Thank you.
BTCScriptMachine
. See BIP65.BTCScript
to add locktime checks.a...
)A...
)I generated script with initWithPublicKeys. Is there a method similar to CScriptID::GetID and CBitcoinAddress(CScriptID::GetID)? Perhaps, it is there but I've spent a whole day looking.
Thanks..
As Swift converts both NSUInteger and NSInteger in objc APIs to signed "Int" type and Chris Lattner provided well-versed argumentation in favor of a single int type, we should play along. Getting rid of unnecessary uint32_t and NSUInteger types in APIs would streamline API usage and reduce amount of compiler complaints.
Most important pieces to update: transaction output/input indexes and BIP32 indexes.
This issue is motivated by real-life usage of CoreBitcoin in a Bitcoin wallet application for iOS.
Some Android wallet I heard support that, so if possible we should too using raw Bluetooth (to be compatible), not only Apple's MultipeerConnectivity framework.
I made a category for BTCKey that automatically detect the network the wallet is for; use if you find it useful:
#import <CoreBitcoin/BTCKey.h>
#import "BTCAddressBcyTestnet.h"
@interface BTCKey (BcyTestnet)
@property(nonatomic, readonly) BTCPublicKeyAddressBcyTestnet* addressByNetwork;
- (id) initWithWIF:(NSString*)wifString detectNetwork:(BOOL)detect;
@end
#import <CoreBitcoin/BTCData.h>
#import <CoreBitcoin/BTCBase58.h>
#import "BTCKey+BcyTestnet.h"
@implementation BTCKey (BcyTestnet)
uint8_t version;
- (id) initWithWIF:(NSString*)wifString detectNetwork:(BOOL)detect {
if (!detect) {
return [self initWithWIF:wifString];
}
const char* addressString = [wifString cStringUsingEncoding:NSASCIIStringEncoding];
NSMutableData* composedData = BTCDataFromBase58CheckCString(addressString);
if (!composedData) return nil;
if (composedData.length < 2) return nil;
// TODO: unsafe
version = ((unsigned char*)composedData.bytes)[0];
BTCPrivateKeyAddress* addr = [BTCPrivateKeyAddress addressWithString:wifString];
if (![addr isKindOfClass:[BTCPrivateKeyAddress class]]) {
return nil;
}
return [self initWithPrivateKeyAddress:addr];
}
- (BTCAddress*) addressByNetwork {
NSData* pubkey = [self publicKey];
// TODO: could cache this value but meh...
if (version == BTCBcyPrivateKeyAddressVersion) {
return [BTCPublicKeyAddressBcyTestnet addressWithData:BTCHash160(pubkey)];
} else if (version == BTCBcyPrivateKeyAddressVersion) {
return [BTCPrivateKeyAddressTestnet addressWithData:BTCHash160(pubkey)];
} else {
return [BTCPrivateKeyAddress addressWithData:BTCHash160(pubkey)];
}
}
@end
So, Heartbleed affects 1.0.1...
Now, considering the device isn't acting as a web server, I'm guessing this probably doesn't compromise wallet security. Am I right?
This will makes it consistent with Apple Obj-C and Swift style guide and consistent with blocks/closures syntax. This should apply to methods, blocks and conditionals.
Originally I was placing opening brace on the new line to have more whitespace around the code to make it easier to read. However, using Meslo font with increased line-height proved to be more efficient and now we can put all braces back on the same line as the related expression.
Before:
if (foo)
{
bar;
}
After:
if (foo) {
bar;
}
In Obj-C it does not matter how you declare a method that has no arguments, no side effects and returns some value. It could be either @property(nonatomic,readonly) Type name
or - (Type) name
.
In Swift, however, it matters:
object.property // => calls a `-property` method
object.method // => returns closure ()->T{ object.method() }
object.method() // => calls a `-method` method.
For consistency and simplicity we should prefer @property(nonatomic, readonly)
and revisit all existing candidate methods to be redeclared as properties.
Can you add some instructions to the README on how to use CoreBitcoin in Swift? I'm able to use the Cocoapod in a single page Objective C iOs project. But if I try import BTCMnemonic
or import CoreBitcoin
in a Swift project - iOs or OS X - I get no such module CoreBitcoin
.
Looking over the BIP32 spec, I believe that these:
CoreBitcoin/CoreBitcoin/BTCKeychain.m
Line 245 in 4c28c50
CoreBitcoin/CoreBitcoin/BTCKeychain.m
Line 258 in 4c28c50
CoreBitcoin/CoreBitcoin/BTCKeychain.m
Line 270 in 4c28c50
Should both be returning derivedKeychainAtIndex:++index hardened:hardened factor:factorOut
instead of nil
. Just wanted to make sure I was correctly interpreting the spec before submitting a PR.
Relevant portion of the spec for Private parent -> Private Child:
In case parse256(IL) ≥ n or ki = 0, the resulting key is invalid, and one should proceed
with the next value for i. (Note: this has probability lower than 1 in 2127.)
and Public parent -> Public Child:
In case parse256(IL) ≥ n or Ki is the point at infinity, the resulting key is invalid, and one
should proceed with the next value for i.
...deterministically? Is this something that needs a bounty?
Format documentation in header files to be compatible with AppleDoc and CocoaDocs.
I cannot get CocoaPods to install CoreBitcoin with the following Podfile
:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
inhibit_all_warnings!
use_frameworks!
pod 'CoreBitcoin', :podspec => 'https://raw.github.com/oleganza/CoreBitcoin/master/CoreBitcoin.podspec'
This produces the following errors:
Updating local specs repositories
Analyzing dependencies
Fetching podspec for `CoreBitcoin` from `https://raw.github.com/oleganza/CoreBitcoin/master/CoreBitcoin.podspec`
Downloading dependencies
Installing CoreBitcoin (0.6.7)
Installing ISO8601DateFormatter (0.7)
Using OpenSSL-Universal (1.0.1.j-2)
[!] The 'Pods' target has transitive dependencies that include static binaries: (/Users/nicolas/devel/ledger-wallet-ios/Pods/OpenSSL-Universal/lib-ios/libcrypto.a and /Users/nicolas/devel/ledger-wallet-ios/Pods/OpenSSL-Universal/lib-ios/libssl.a)
Are there any workarounds? I know I can remove the use_frameworks!
option, but I need it for other target dependencies using Swift.
Thanks!
Currently BTCKey uses simple HMAC-SHA256 to compute k from private key and tx hash. It works just fine, but it's better to support the "standard" RFC6979 (I simply didn't have enough time to implement it fully).
Pros:
Being standard, signatures from different implementations can be audited using the same algorithm.
(Not a real benefit) RFC6979 checks if k is out of bounds and sequentially computes next values until they are good. Hitting this case is highly improbable (2^-127 chance).
I Can verify a signature for message in corebitcoin but when I try to verify the signature in other frameworks such as bitcoin.j the signature is not valid, what is the correct way to get the signature as a string?
BTCKey * newKey = [[BTCKey alloc] init];
NSData * sig = [newKey signatureForMessage:@"hello world"];
NSLog(@"sig:%@",sig.base58String);
NSLog(@"sig:%@",sig.BTCHash256.hex);
NSLog(@"sig:%@",sig.hex);
if([newKey isValidSignature:sig forMessage:@"hello world"]){
NSLog(@"valid");
}
else{
NSLog(@"not valid");
}
Hi Oleganza !
I have one question on the BTCKey object.
There is a way to force the "L" as first letter in the address ? (I'm thinking about LiteCoin).
Cheers
See BTCFancyEncryptedMessage
: it uses automatic sender's private key and allows to shorten recipient's key to a hash or a fraction of a hash. For compatibility with Bitcore ECIES we still should allow explicit and full sender's pubkey mention in the payload.
We need to update API so that instead of ad-hoc mainnet/testnet flags or method variants we pass in BTCNetwork instance. That would allow for more streamlined API and flexibility in adjusting network settings for testing (one could clone testnet or mainnet and tune a few parameters).
These classes need to be updated:
BTCNetwork
should have setDefault
and default
class methods to set the default network. Default default is mainnet
.
See Chain-iOS SDK to have a taste of it.
For some reason, I cannot build the libraries on Mac OS 10.11 and XCode 7.1.1.
After running update_openssl.sh
and build_libraries.sh
, the build only create a full framework for OS X. The iOS framework is incomplete due to build errors.
I would like a library I can use to pass messages to my mobile app via the blockchain.
Issue when trying to install via cocoa pods: "The target has transitive dependencies that include static binaries" .
When trying to run the script ./update_openssl.sh it gives the error: "SDK "iphoneos" cannot be located".
Anyone know what to do to fix these issues?
We probably use that in parallel with OpenSSL in BTCKey
, BTCBigNumber
and BTCCurvePoint
implementations, so we can use both to verify signatures or just one if we are feeling lucky.
The first step would be to adapt libsecp256k1
to CocoaPods.
File not found on https://github.com/oleganza/CoreBitcoin/blob/master/CoreBitcoin/BTCBase58.m#L5 in Xcode
I did the installation following the steps, but after referencing the .framework file for my iPhone application I`m getting this error message.
I tried changing the project file to ENABLE_BITCODE, as suggested by this error message - no success. Any ideas?
ld: '(...)/CoreBitcoin-master/binaries/iOS/CoreBitcoin.framework/CoreBitcoin' does not contain bitcode. You must rebuild it with bitcode enabled (Xcode setting ENABLE_BITCODE), obtain an updated library from the vendor, or disable bitcode for this target. for architecture arm64
I got the single signature part from your BTCTransaction+Tests file. How is it done for multisig key?
Thanks..
I am trying to generate Public Key from the X, Y Component and Curve that I received from Server. Below code I am using but not able to generate Public Key.
void* getPublicKeyFromX_Y(const void *xInput, int xLen, const void *yInput, int yLen, int outputLength)
{
EC_GROUP *group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
BN_CTX *ctx = BN_CTX_new();
EC_POINT *point = EC_POINT_new(group);
void *pubKey = NULL;
BIGNUM *x = BN_bin2bn(xInput, xLen, NULL);
BIGNUM *y = BN_bin2bn(yInput, yLen, NULL);
if(EC_POINT_set_affine_coordinates_GFp(group, point, x, y, ctx))
{
BIGNUM publicKeyBn;
BN_init(&publicKeyBn);
EC_POINT_point2bn(group, point, POINT_CONVERSION_UNCOMPRESSED, &publicKeyBn, NULL);
int length = 65; //Uncompressed, For compressed, it should be 33
unsigned int offset = length - BN_num_bytes(&publicKeyBn);
pubKey = calloc(1, length * sizeof(char *));
outputLength = length;
BN_bn2bin(&publicKeyBn, pubKey+offset);
BN_clear(&publicKeyBn);
EC_GROUP_free(group);
// EC_KEY *publicKey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
// if(EC_KEY_set_public_key(publicKey, point))
// {
// printf("here");
// }
}
BN_free(x);
BN_free(y);
return pubKey;
}
+(NSData *)getPublicKeyFromX:(NSData *)xInput Y:(NSData *)yInput
{
NSData *pubKey = nil;
int outputLength = 65;
void *pubkey = getPublicKeyFromX_Y([xInput bytes],(int)[xInput length],[yInput bytes],(int)[yInput length], outputLength);
pubKey = [[NSData alloc] initWithBytes:pubkey length:outputLength];
return pubKey;
}
Later I found this Library and was exploring my solution but didn't found any thing related.
Does CoreBitcoin contains my solution? How and from where should I attack my problem?
If this question is irrelevant for CoreBitcoin, please feel free to close. But I found it to be somewhat related and hence posting it to find my solution.
Help is much appreciated. Thanks.
I haven't looked at the code, so maybe that's what you're doing. Either way, I think this question should be answered prominently in the README, because it's the first thing a lot of folks are going to think/ask.
Hi,
I am struggling to build a raw unsigned and signed transaction and was hoping you could help give me a bit of advise.
I am getting this error after i try and print the result of BTCTransactionBuilder:
error = Error Domain=com.oleganza.CoreBitcoin.TransactionBuilder Code=3 "(null)"
Here is the full function:
`func parseAddress(address: String) {
print("getAddressTransactionInputs")
var url:NSURL!
url = NSURL(string: "https://testnet.blockchain.info/unspent?active=\(address)")
let task = URLSession.shared.dataTask(with: url! as URL) { (data, response, error) -> Void in
do {
if error != nil {
print(error as Any)
} else {
if let urlContent = data {
do {
let jsonAddressResult = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableLeaves) as! NSDictionary
if let utxoCheck = jsonAddressResult["unspent_outputs"] as? NSArray {
var balance:Double = 0
for utxo in utxoCheck {
let utxoDictionary:NSDictionary! = utxo as! NSDictionary
print("utxo = \(utxoDictionary)")
var amount = Double()
var transactionHash = String()
var transactionOutputN = Double()
var lockingScript = String()
var transactionIndex = Double()
amount = utxoDictionary["value"] as! Double
transactionHash = utxoDictionary["tx_hash"] as! String
transactionOutputN = utxoDictionary["tx_output_n"] as! Double
lockingScript = utxoDictionary["script"] as! String
transactionIndex = utxoDictionary["tx_index"] as! Double
/*
print("transactionHash =\(transactionHash)")
print("transactionOutputN =\(transactionOutputN)")
print("lockingScript =\(lockingScript)")
print("transactionIndex =\(transactionIndex)")
*/
balance = balance + amount
let script = BTCScript.init(hex: lockingScript)
let txId = transactionHash.data(using: .utf8)
let newInput = BTCTransactionInput()
newInput.previousHash = txId
newInput.previousIndex = UInt32(transactionIndex)
newInput.value = BTCAmount(balance)
newInput.signatureScript = script
let address = BTCAddress.init(string: "mxxky7EDvEVa4z9pwenveSMcj6L3CJ85di")
let primaryOutput = BTCTransactionOutput(value: 129870000, address: address)
let newTransaction = BTCTransactionBuilder()
newTransaction.shouldSign = false
let transaction = BTCTransaction()
transaction.addInput(newInput)
transaction.addOutput(primaryOutput)
transaction.fee = 130000
do {
let transactionRaw = try newTransaction.buildTransaction()
print("transactionRaw = \(transactionRaw)")
} catch {
print("error = \(error as Any)")
}
}
}
} catch {
print("JSon processing failed")
}
}
}
}
}
task.resume()
}`
Thanks to anyone very much for any help or letting me know what i'm doing wrong.
Currently only iOS is supported for both QR generator and scanner.
let keychain = BTCKeychain(seed: (seedHash() as NSString).ny_dataFromHexString())
let one = keychain.rootKey.publicKeyAddress.base58String()
let two = BTCKey(privateKey: keychain.rootKey.privateKey).publicKeyAddress.base58String()
println("\(one) differs from \(two)")
"1EJYiQKcb7dZHeSiEq6YG4xMoTx6SoBQWL differs from 1JTEnEoYeaaCoqGH45zLzTpFKFab4oJ7Lh"
Not getting the same public key address for some reason here
Today Xcode 6.3 with Swift 1.2 is out and we can use new annotations: __nullable and __nonnull (see https://developer.apple.com/swift/blog/?id=25)
We should eventually annotate all methods and properties explicitly. Use of audited regions (NS_ASSUME_NONNULL_BEGIN etc.) should be used sparingly to avoid making mistakes or making the code hard to follow.
We need:
I have used BTCScript create a multiSig address. But I use this address to send bitcoin that is not work。
I use "insight.bitpay.com/api/" to send bicoin.
The BTCTransaction+Tests only have single sign transaction.
Is there any MultiSig transaction unit test?
How can I verify that it is a valid address?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.