Transaction on bitcoin address derived from bitcoinjs-lib not showing in Bitcoin core - bitcoin

I have generated the xpub using bip32.org and derieved random address using xpub
var hdNode = bitcoinjs.HDNode.fromBase58(derivedPubKey);
hdNode.derive(index).pubKey.getAddress().toString();
the Private wif generated via bip32.org imported in the Bitcoin core. On transferring amount on the address generated by above code., amount is not showing in my bitcoin-core..

If you have imported the main pubkey into Core but the address you send to is a derived address then you are just sending to different address than you are expecting the funds to receive at.
Every derived address has its own private key so you have to import the keys of individual derived addresses not just the key of the chain:
var addr = hdNode.derive(i);
/* Derived address: */
addr.getAddress();
/* Corresponding privkey: */
addr.keyPair.toWIF();
In fact every derived address is possibly also a new chain (derive() returns a new HDNode). Also your hdNode is intended to be used only for address derivation yet it has own address too (the one you have sent your funds too), just because there are no separate datatypes for addresses and for chains. To access that funds just generate private key without derivation:
hdNode.keyPair.toWIF();
On the other hand if you use Electrum instead of Core you may just extract the main key of one of address chains of an Electrum wallet (it does not work the opposite way as Electrum uses checksum for wallet seed and you cannot just import non-electrum chain). This way you will be able to independently generate new addresses (also just new addresses without privKeys, for security reasons) which would be recognized by the wallet without importing them explicitly.
By the way, https://bitcoin.stackexchange.com/ is better place to ask bitcoin-related questions.

Yes you can create address from private key using below code
const bitcoin = require('bitcoinjs-lib');
let testnet = bitcoin.networks.testnet;
const keyPair = bitcoin.ECPair.fromWIF('cQnWufBcGz5fDtAPH8DVzrayXY1BJVCohCSHhgHXV8xnWfkGKQGL', testnet )
const { address } = bitcoin.payments.p2pkh({ pubkey: keyPair.publicKey })
console.log(address)

Related

Obtain Private Key Corresponding to Address in HD Wallet with BlockCypher API?

We are using BlockCypher API to create transaction in a HD Wallet.
As a return object, you'll receive a TXSkeleton containing a
slightly-more complete TX alongside data you need to sign in the
tosign array. You'll need this object for the next steps of the
transaction creation process.
Locally Sign Your Transaction
With your TXSkeleton returned from the New Transaction Endpoint, you
now need to use your private key(s) to sign the data provided in the
tosign array.
$PRIVATEKEY here is a hex-encoded private key corresponding to the input from address CEztKBAYNoUEEaPYbkyFeXC5v8Jz9RoZH9
My problem is how do we obtain the private key of each address in HD Wallet? With HD Wallet addresses are generated using the Derive Address Endpoint. This returns a HDWallet object which contains and HDChain object which contains an HDAddress Object. The HDAddress object contains address, path and public.
An HD Address object contains an address and its BIP32 HD path
(location of the address in the HD tree). It also contains the
hex-encoded public key when returned from the Derive Address in Wallet
endpoint.
As you can see, the private key is not included in HDAddress object response. So how can we know the private key to use with tosign method if the private key is not included in HDAddress object response? And without access to private key, how can we sign the **tosign** array?
Thanks

Issues during implementation of custom ETH settler

I have investigated and played with corda-settler project. Following the recommendations within the documentation, I have created a custom ethereum module (with an outline similar to the ripple module), providing the option to settle obligations using off-ledger payments in ETH. The implementation (https://github.com/vladichhh/corda-settler)
consists of the following significant pieces:
flows
MakeEthPayment
services
ETHClient
ETHService
types
EthPayment
EthSettlement
token
registered DigitalCurrency for ETH
oracle
added logic for ETH payment verification
MakeEthPayment.kt
#Suspendable
override fun makePayment(obligation: Obligation<*>, amount: Amount<T>): EthPayment<T> {
// get ETHService client
val ethClient = serviceHub.cordaService(ETHService::class.java).client
val recipient = obligation.settlementMethod?.accountToPay.toString()
val amountToSend = amount.quantity.toString()
// trigger ETH transfer
val txHash = ethClient.sendEth(recipient, amountToSend)
// return the payment
return EthPayment(txHash, amount, PaymentStatus.SENT)
}
ETHClient.kt
fun sendEth(recipient: String, amount: String): String {
val weiAmount: BigInteger = Convert.toWei(amount, Convert.Unit.GWEI).toBigInteger()
val credentials: Credentials = WalletUtils.loadCredentials(walletPassword, walletFile)
val transactionReceipt: TransactionReceipt = Transfer
.sendFunds(web3j, credentials, recipient, BigDecimal(weiAmount), Convert.Unit.WEI)
.send()
return transactionReceipt.transactionHash
}
In order to send the required ETH amount to the specified recipient account, we have to do some Ethereum specific stuff:
we are connecting to Ethereum public blockchain environment, using “web3j” library
in order to trigger am Etherem transaction and transfer specified ETH amount, "web3j" requires an access to the file, containing encrypted sender's wallet
thus we have to provide password (to decrypt wallet) and location of the file, containing encrypted sender's wallet
And here are the issues:
I got the exception that the file could not be found, no matter where I am putting it. I have checked even the “swift” implementation and tried to use the class loader to load my file, but without success.
I suppose, the file with encrypted sender’s wallet should be located on one of the following places:
corda-settler/ethereum/src/main/resources/file.tmp
corda-settler/cordapp/src/main/resources/file.tmp
Finally I have hardcoded the location in that way:
/Users/vladimirhristov/WebstormProjects/Corda/corda-settler/cordapp/src/main/resources/file.tmp
and seems that the file was found but got another exception:
java.lang.OutOfMemoryError - screenshot
Seems that the operation of wallet decryption is highly consuming, which breaks maybe the flow. There is an option to reduce the algorithm complexity of the wallet generation, which will reflect in lower resources required to decrypt the same wallet at the next step, but this will reduce the security as well.
And here are my three basic questions ...
How could I specify (location/mechanism) and make flow to find successfully my file, containing the sender’s encrypted wallet ?
How could I access a files in the flow, or if there is another mechanism to attach only the file with encrypted wallet and pass the decryption to core Corda ?
Do I need just to increase node resources (tuning JVM params increasing -Xms/-Xmx) in order to avoid OutOfMemoryError ?
Content of the file (containing encrypted sender’s wallet):
file.tmp
{"version":3,"id":"ecb51768-8564-498a-bb11-3a5a5c8dc0bb","address":"2bafc482bd227dfd5ba250521a00be3a4cc88bbd","crypto":{"ciphertext":"e0511415792dfa7221ba1b8f32b8ec98e1410f45e612e2100df1aceddfdb22bd","cipherparams":{"iv":"7ffa2af08f502c63d57e62440ad77539"},"cipher":"aes-128-ctr","kdf":"scrypt","kdfparams":{"dklen":32,"salt":"8051a5df1c02eb3eba81d2920fbb84b76b948a1248bbba62ffff684e733948cf","n":131072,"r":8,"p":1},"mac":"be23fe0e261ba38892581d80afd0c86563748377b5cc702b6ed3285a13cceff6"}}
I will appreciate any help! Thanks in advance :)
VERY strange that Corda is giving you an out of memory error when running that flow.
I'd actually say that we'd need to be able to see the code for the flow in order to know how it could have run out of memory.
Are you running it in a container? Just make sure that you're meeting the requirements to run a JVM with an application on top.
tl;dr use a 8GB RAM machine to run your Corda node on the latest version of corda that should hopefully solve this issue.
Here's the docs page on the memory requirements;
https://docs.corda.net/docs/corda-enterprise/4.5/node/performance-results.html#sizing

How to test contract with multiple accounts / addresses in truffle?

I want to test my truffle contract with multiple msg.sender addresses. Like "the first user sell token, the second user buys this token". For one address I simply write something like contract.buy.value(10 wei)();. But where I could get another address and how to send money from him?
I write my tests on solidity, not on javascript.
as you can see in the Truffle docs, you can specify two different accounts to interact with your deployed smart contract like below (Metacoin example):
var account_one = "0x1234..."; // an address
var account_two = "0xabcd..."; // another address
var meta;
MetaCoin.deployed().then(function(instance) {
meta = instance;
return meta.sendCoin(account_two, 10, {from: account_one});
}).then(function(result) {
// If this callback is called, the transaction was successfully processed.
alert("Transaction successful!")
}).catch(function(e) {
// There was an error! Handle it.
})
This is about how you can do with your own created token.
If you want to transfer Ether between accounts, you can specify accounts in your truffle execution file (a javascript file). And these accounts may come from your configured local blockchain (Ganache, if you are using Truffle Suite to test your smart contract, it will provide you with several accounts and you can configure these by yourself).
Moreover, you may need javascript API to specify the sender and receiver: web3.eth.sendTransaction.
First time to answer a question, hope this will help.

how to encrypt the chat message with multiple people public key together and restore the message?

I have a application with two users and one middle man, all of them holding the private and public key, To make the secured chat, two users and one middle man are all sending the public key and generate a secured channel. After establishing the channel, the middle man doesn't have the ability to see the encrypted message unless one of the user is sending his own key to the middle man.
i am not very familiar with cryptography, so for this app i know how to encrypt and decrypt the message.
encrypt(data) {
try {
var cipher = Crypto.createCipher('aes-256-cbc', this.password);
var encrypted = Buffer.concat([cipher.update(new Buffer(JSON.stringify(data), "utf8")), cipher.final()]);
FileSystem.writeFileSync(this.filePath, encrypted);
return { message: "Encrypted!" };
} catch (exception) {
throw new Error(exception.message);
}
}
but I don't know how to establish the encrypted channel from the stakeholders' key, and how can the one middle to see the message using his key and one of users' key?
is there a way to accomplish this using the cryptography?
I'm not sure I completely understand, but I think if you want to go with a system that doesn't use public key crypto I would suggest a system using 2 stages of encryption, actually a lot like PGP only both stages use symmetric keys-
1) There is a fixed session key generated by the first person in the chat, this can be a randomly generated number.
2) This session key is then encrypted by the keys belonging to every new member of the chat group and individually sent to them.
3) The new members decrypt with their own unique keys to get the plaintext session key back.
4) This session key is subsequently used to decrypt the messages sent to all participants. The same key can also be used to encrypt and send any new messages from any entitled participant(i.e. has the valid session key) on the chat group.
This is used in some systems but it relies on the unique keys being securely transmitted, in the first instance. If this condition can't be met, it's a problem that can be solved with public key crypto to build an end-to-end secure message system like PGP, whatsapp, etc.

Developing a Service with API Keys (starting point)

Looked on google and couldn't find anything.
Any good resources to get started designing my backend for a RESTless webapp thats going to rely heavily on API keys.
I know how to write restless webservices etc, just never used API-keys. Generally do people just generate guids for users etc?
Here's how I'm creating API keys for a web service:
string CreateApiKey(int length)
{
var bytes = new byte[length * 2];
using (var rng = new RNGCryptoServiceProvider())
rng.GetBytes(bytes);
var chars = Convert.ToBase64String(bytes)
.Where(char.IsLetterOrDigit)
.Take(length)
.ToArray();
var key = new String(chars);
return key;
}
GUID's are typically not "random" enough and can be easily guessed by the bad-guys.
Take some "random" data like the user's password hash, some random numbers and run the result through sha1 or a similar hash function.
If you want one API key per account, simply add it to the account metadata table. Otherwise use a table linked to the accountIds to store the api keys.
Server side use a cache using the api-key as the key to store temporarily the account metadata so you only need to go to the db once per session.
And of course everything must go over https to avoid that the API key be stolen.
Now if your service is "session" oriented you can consider using a temporary session key so you do not need to expose the API key. Look for public key encryption to investigate this further.