GithubHelp home page GithubHelp logo

consenlabs / token-core-ios Goto Github PK

View Code? Open in Web Editor NEW
879.0 47.0 228.0 17.88 MB

a blockchain private key management library on iOS

License: Apache License 2.0

Swift 99.51% Ruby 0.41% Objective-C 0.08%
ethereum eos bitcoin blockchain

token-core-ios's Introduction

TokenCore

TokenCore is a blockchain library. TokenCore provides the relatively consistent API that allows you to manage your wallets and sign transactions in BTC, ETH and EOS chains simultaneously. In addition, TokenCore introduces the concept of 'identity', you can use the same mnemonic to manage wallets on the three chains.

Installation

To install TokenCore, use CocoaPods and add this to your Podfile:

pod "TokenCore", git: "https://github.com/consenlabs/token-core-ios.git", branch: "master"

Run the Example

The example show how to manager the wallet and sign transaction, the eos sign will coming soon.

$ cd Example
$ pod install

Try the API

Create new Identity and derive the eth, btc wallets

// You should create or recover Identity first before you create other wallets
do {
  var metadata = WalletMeta(source: .newIdentity)
  metadata.network = Network.mainnet
  metadata.segWit = .p2wpkh // .p2wpkh means that the derived btc wallet is a SegWit wallet
  metadata.name = "MyFirstIdentity"
  let (mnemonic, identity) = try Identity.createIdentity(password: TestData.password, metadata: metadata)
  let ethereumWallet = identity.wallets[0]
  let bitcoinWalelt = identity.wallets[1]
} catch {
  print("createIdentity failed, error:\(error)")
}

Export Wallet

let prvKey = try WalletManager.exportPrivateKey(walletID: ethereumWallet.walletID, password: TestData.password)
print("PrivateKey: \(prvKey)")
let mnemonics = try WalletManager.exportMnemonic(walletID: ethereumWallet.walletID, password: TestData.password)
print("Mnemonic: \(mnemonics)")
let keystore = try WalletManager.exportKeystore(walletID: ethereumWallet.walletID, password: TestData.password)
print("Keystore: \(keystore)")

// output:
// PrivateKey: f653be3f639f45ea1ed3eb152829b6d881ce62257aa873891e06fa9569a8d9aa
// Mnemonic: tide inmate cloud around wise bargain celery cement jungle melody galaxy grocery
// Keystore: {"id":"c7575eba-3ae3-4cc3-86ba-2eb9c6839cad","version":3,"crypto":{"ciphertext":"7083ba3dd5470ba4be4237604625e05fa6b668954d270beb848365cbf6933ec5","mac":"f4f9ea8d42ff348b11fc146c396da446cc975309b3538e08a58c0b218bddd15d","cipher":"aes-128-ctr","cipherparams":{"iv":"db3f523faf4da4f1c6edcd7bc1386879"},"kdf":"pbkdf2","kdfparams":{"dklen":32,"c":10240,"prf":"hmac-sha256","salt":"0ce830e9f888dfe33c31e6cfc444d6f588161c9d4128d4066ee5dfdcbc5d0079"}},"address":"4a1c2072ac67b616e5c578fd9e2a4d30e0158471"}

SignTransaction

let signResult = WalletManager.ethSignTransaction(
        walletID: String,
        nonce: String,
        gasPrice: String,
        gasLimit: String,
        to: String,
        value: String,
        data: String,
        password: String,
        chainID: Int
      )
let signedTx = signResult.signedTx // This is the signature result which you need to broadcast.
let txHahs = signResult.txHash // This is txHash which you can use for locating your transaction record

Troubleshooting

For macOS 10.14 Mojave and Xcode 10, install /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg since Xcode command line tools don't install to /usr/include anymore.

TODO

  • Test on Objective-C
  • upgrade the BigInt from 3.0 to 3.1

Copyright and License

  Copyright 2018 imToken PTE. LTD.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

Thanks and more info

Thanks bitcoinj, CoreBitcoin and others library.

token-core-ios's People

Contributors

ashchan avatar euforic avatar kaichen avatar linknoweasy avatar tualatrix avatar xuneal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

token-core-ios's Issues

Why the ETC keystore "address" is not support "0x....." but "......"

Why the ETC keystore "address" is not "0x....." but "......"
if other app keystore 's "address" is "0x...." the wallet is nil
but the imtoken app is support all above types.

Please think twice and weather need to update the sdk. Or tell me ,what should I do if the user use keystore with address "0x...."
eg:

let json = "{"address":"0xc9cbc3bcef3b50d765a1527d9a63a6c9eda7e7bd","id":"e2ef2600-8928-4264-a3e9-e2129584e995","version":3,"crypto":{"cipher":"aes-128-ctr","ciphertext":"3d4c5e461b05bd3be1719c1c420c66390307bd7997204e5d41aa7c9c8b0b6d6d","cipherparams":{"iv":"8621503dbc68031b79dd28289b93c1b1"},"kdf":"scrypt","kdfparams":{"dklen":32,"n":4096,"p":6,"r":8,"salt":"26552d24acb8ea32aa35827d1cce999458eed744750ccc81c00055b2c2dfc793"},"mac":"4148aeb208e6ce123eacd8b5cdbfe45cdaafe69c3c821ceb2ca7a99de31f4282"}}"//TestHelper.loadJSON(filename: "v3-scrypt-testpassword")
let password = "q"

do {
  let keystore = try json.tk_toJSON()
  let meta = WalletMeta(chain: .eth, source: .keystore)
  let wallet = try WalletManager.importFromKeystore(keystore, encryptedBy: password, metadata: meta)

}
//the wallet is nil because of "0xc9cbc3bcef3b50d765a1527d9a63a6c9eda7e7bd"

BTC 签名问题

通过导入助记词生成Btc钱包地址,在transaction签名时, WalletManager.btcSignTransaction(walletid ,to ,fee ....)传入了该地址对应的walletid等信息,签名后得到的result.signedTx ,但广播到链上的时候提示 Missing input.可能是签名时得到的密钥有错

about keystore BTCMnemonicKeystore.swift

/// Generate app specific key and IV!
public static var commonKey = "00000000000000000000000000000000"
public static var commonIv = "00000000000000000000000000000000"
how to generate value

some questions about code (请教一下)

Why is it in the initialization method in the Identity class. The default is eth and btc, not eos? Is it based on any considerations?

try deriveWallets(for: [.eth, .btc]......)

为什么在 Identity 类中的初始化方法中. 默认生成的是 eth 和 btc, 不包含 eos 呢?是基于什么考虑的呢

BTC找零地址为什么不是钱包本身的地址?

WalletManager.swift里面,代码如下:
let changeAddress = changeKey.address(on: isTestnet ? .testnet : .mainnet, segWit: segWit)

我打印出来changeAddress是一个奇怪的地址,找零的钱都不见了?
为什么changeAddress不直接用 wallet.address?

提供OC的demo

感谢作者的开源,由于项目是OC功能,在集成的时候失败了,作者能提供一份oc的demo吗,这样也更利于这个库的推广

咨询下,示例里面有eos签名的,但是data看起来是一个16进制,确认下是否把字典转成16进制data进行sign。

///主要这里的data一开始看起来就是16进制,而不是一个字典明文,不太清楚这个16进制data如何加工得来?
//未处理的data 字典
{"compression": "none",
"transaction": {
"expiration": "
....//忽略
}

//示例
let wallet = try! WalletManager.importEOS(from: TestData.mnemonic, accountName: "", permissions: [], metadata: WalletMeta(chain: .eos, source: .mnemonic), encryptBy: TestData.password, at: BIP44.eosLedger)
let txs = [
EOSTransaction(
data: "c578065b93aec6a7c811000000000100a6823403ea3055000000572d3ccdcd01000000602a48b37400000000a8ed323225000000602a48b374208410425c95b1ca80969800000000000453595300000000046d656d6f00",
publicKeys: ["EOS88XhiiP7Cu5TmAUJqHbyuhyYgd6sei68AU266PyetDDAtjmYWF"],
chainID: TestData.eosChainID
)
]
let result = try! WalletManager.eosSignTransaction(walletID: wallet.walletID, txs: txs, password: TestData.password)
print(result[0])
XCTAssertEqual(1, result.count)
XCTAssertEqual(
result[0],
EOSSignResult(hash: "6af5b3ae9871c25e2de195168ed7423f455a68330955701e327f02276bb34088", signs: ["SIG_K1_KjZXm86HMVyUd59E15pCkrpn5uUPAAsjTxjEVRRueEvGciinxRS3sATmEEWdkb8hRNHhf6SXofsz4qzPdD6mfZ67FoqLxh"])
)

How to export BTC privateKey?

How to export BTC privateKey?
I try the method from WalletManager
exportPrivateKey(walletID: String, password: String) throws -> String
but the value is not a BTC privateKey

Failed to download 'TokenCore'.

When I install the TokenCore with CocoaPods,there is an issue:

pod install
Analyzing dependencies
Pre-downloading: `TokenCore` from `[email protected]:consenlabs/token-core-ios.git`, branch `master`

[!] Error installing TokenCore
[!] Failed to download 'TokenCore'.

here is my Podfile:

# Uncomment the next line to define a global platform for your project
platform :ios, '9.3'

target 'WalletSample' do
  # Comment the next line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for WalletSample
  pod "TokenCore", :git => "[email protected]:consenlabs/token-core-ios.git", :branch => 'master'
  
end

创建 `Identity ` 耗时问题

image
image

现象: 在 AppleDelegate 测试了一下耗时. 创建一个 Identity 耗时 12 秒左右。
环境: Xcode 10.1 , 真机 iPhone 7. 12.0.1 系统,
引用方式: clone 工程后. 修改了PodFile pod "CryptoSwift", "0.10.0" , 编译后工程引用 TokenCore 动态库

疑惑的是. 运行测试用例时候, 创建耗时大概 0.5 秒
期待您的回复

Should EOS wallet be created automatically when creating an Identity?

//filePath: Source/Wallet/Identity.swift

  init(metadata: WalletMeta, mnemonic: String, password: String) throws {
    keystore = try IdentityKeystore(metadata: metadata, mnemonic: mnemonic, password: password)
    //_ = try deriveWallets(for: [.eth, .btc,.eos], mnemonic: mnemonic, password: password) ? 
    _ = try deriveWallets(for: [.eth, .btc], mnemonic: mnemonic, password: password)

    _ = Identity.storage.flushIdentity(keystore)
  }

Ethereum's keccak256

Test of Encryptor.Keccak256 gives that the hash of an empty string "" is "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470"
However, seems like that it's not the standard Ethereum has been using?

OC环境下 pod 后编译的问题

OC环境下编译 TokenCore-Swift.h 里import CoreBitcoin 报错,提示Module ‘CoreBitcoin’ not found,有好的解决方法吗?

EOS签名与EOS4J的签名结果不一样

你好,我们在使用过程中,使用了tokencore里面的测试用例,iOS上跑出来的结果符合测试用例,但是与用EOS4J库或Go库签名出来的结果不一致,请问是什么原因呢。。。

How do I use the private key to derive the public key?

I know this "let basicWallet = [try WalletManager.importFromPrivateKey(privateString as String, encryptedBy: password as String, metadata: metadata, accountName: address as String)]"
but this methods need an address.How can I get the publicKey without address,just with privateKey?

关于比特币转账

public static func btcSignTransaction(
walletID: String,
to: String,
amount: Int64,
fee: Int64,
password: String,
outputs: [[String: Any]],
changeIdx: Int,
isTestnet: Bool,
segWit: SegWit
) throws -> TransactionSignedResult

您好,转账时参数outpus是传以下的数组吗 outputs
NSError* error = nil;
NSArray* outputs = [[[BTCBlockchainInfo alloc] init] unspentOutputsWithAddresses:@[ [BTCAddress addressWithString:@"1FRVQUbzFSYB6VPdz1KowbDog7v679pojT"] ] error:&error];

但是好像不对,另外changeIdx也不知如何生成,麻烦坐着可否提供个简单的 demo呢 谢谢

About EOS transfer

public static func eosSignTransaction(
walletID: String,
txs: [EOSTransaction],
password: String
) throws -> [EOSSignResult] {
guard let wallet = Identity.currentIdentity?.findWalletByWalletID(walletID) else {
throw GenericError.walletNotFound
}
What is the use of this method? Is it just for signatures?Or I can use it to transfer money?

钱包操作报 walletNotFound

创建多个钱包,只生成一个identity.json文件?创建多个钱包后,做钱包导出操作,只有最新创建的那个钱包可以导出成功,之前的钱包都报 walletNotFound , 这是什么情况?

OC建立的主工程 集成token-core遇到问题

OC建立的主工程使用cocoapod导入#import "TokenCore-Swift.h"文件中的CoreBitcoin module无法找到。

系统生成的中间文件TokenCore-Swift.h中 有@import CoreBitcoin . 但编译起来提示module not fuound.目前还没找到解决办法。

关于BTC转账

1.关于初始化UTXO 的疑问
调用以下方法时:
@objc public init(txHash: String, vout: Int, amount: Int64, address: String, scriptPubKey: String, derivedPath: String?, sequence: UInt32 = 4294967295)
我拿到一个未花费交易的数组,去初始化一个UTXO时,这个address参数,该怎么理解?是所有都传主地址的address,还是要传这个未花费交易对应的地址。

2.生成签名对象的疑问
调用以下方式时:
@objc init(utxos: [UTXO], keys: [BTCKey], amount: Int64, fee: Int64, toAddress: BTCAddress, changeAddress: BTCAddress)
这个BTCKey的数组,该怎么初始化。我现在用下面的代码初始化,能转账成功,但是不确定是否正确。

for (int i= 0; i < utxoArray.count; i++) {
BTCMnemonic *m = [[BTCMnemonic alloc]initWithWords:words password:nil wordListType:BTCMnemonicWordListTypeEnglish];
BTCKeychain * keychain = m.keychain;
NSString *path = [NSString stringWithFormat:@"m/49'/0'/0'/0/%d",i];
BTCKey *key = [keychain keyWithPath: path];
key.publicKeyCompressed = YES;
[keyArray addObject:key];
}

这个path 以m/49'/0'/0'/0为基数,后面拼接循环的index值。实际开发中我有区分:是否隔离见证和是否是主网。这个地方仅做一个示例。

希望我表达清楚了我的疑惑。期望您的回复,如果有可能提供一份完整的demo 就更好了

A Bug?

else if (opcode == OP_PUSHDATA2) {
uint16_t dataLength;

        if (offset + sizeof(dataLength) > length) return nil;
        
        memcpy(&dataLength, bytes + offset + sizeof(opcode), sizeof(dataLength));
        dataLength = CFSwapInt16LittleToHost(dataLength);
        
        NSUInteger chunkLength = sizeof(opcode) + sizeof(dataLength) + dataLength;
        
        if (offset + chunkLength > length) return nil;
        
        chunk.range = NSMakeRange(offset, chunkLength);
    } else if (opcode == OP_PUSHDATA4) {
        uint32_t dataLength;
        
        if (offset + sizeof(dataLength) > length) return nil;
        
        memcpy(&dataLength, bytes + offset + sizeof(opcode), sizeof(dataLength));
        dataLength = CFSwapInt16LittleToHost(dataLength);
        
        NSUInteger chunkLength = sizeof(opcode) + sizeof(dataLength) + dataLength;
        
        if (offset + chunkLength > length) return nil;
        
        chunk.range = NSMakeRange(offset, chunkLength);
    }

在 opcode == OP_PUSHDATA4 时,是否应该使用 CFSwapInt32LittleToHost,而不是CFSwapInt16LittleToHost

cocoapods error

Analyzing dependencies
Pre-downloading: TokenCore from [email protected]:consenlabs/token-core-ios.git, branch master

[!] Error installing TokenCore
[!] Failed to download 'TokenCore'.

pod search TokenCore
[!] Unable to find a pod with name, author, summary, or description matching TokenCore

大佬们, ETH钱包, 如何进行ERC20代币交易啊

let signResult = WalletManager.ethSignTransaction(
walletID: String,
nonce: String,
gasPrice: String,
gasLimit: String,
to: String,
value: String,
data: String,
password: String,
chainID: Int
)

这个api是 eth交易的吧, 代币ERC20如何写交易啊

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.