本文整理汇总了C++中CKey::MakeNewKey方法的典型用法代码示例。如果您正苦于以下问题:C++ CKey::MakeNewKey方法的具体用法?C++ CKey::MakeNewKey怎么用?C++ CKey::MakeNewKey使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类CKey
的用法示例。
在下文中一共展示了CKey::MakeNewKey方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: Init
void CAccountViewTest::Init() {
vRandomKeyID.reserve(VECTOR_SIZE);
vRandomRegID.reserve(VECTOR_SIZE);
vAccount.reserve(VECTOR_SIZE);
for (int i = 0; i < VECTOR_SIZE; i++) {
CKey key;
key.MakeNewKey(false);
CPubKey pubkey = key.GetPubKey();
CKeyID keyID = pubkey.GetID();
vRandomKeyID.push_back(keyID);
}
for (int j = 0; j < VECTOR_SIZE; j++) {
CRegID accountId(10000 + j, j);
vRandomRegID.push_back(accountId);
}
for (int k = 0; k < VECTOR_SIZE; k++) {
CSecureAccount account;
account.llValues = k + 1;
account.keyID = vRandomKeyID.at(k);
vAccount.push_back(account);
}
}
示例2: CBitcoinSecret
BOOST_FIXTURE_TEST_CASE(rpc_getnewaddress_test, RPCTestWalletFixture)
{
BOOST_CHECK(pwalletMain != NULL);
LOCK2(cs_main, pwalletMain->cs_wallet);
CKey key;
CPubKey pubkey;
string strRPC = "";
Value r;
// show import key tests
key.MakeNewKey(true);
pubkey = key.GetPubKey();
// import private key
strRPC = "importprivkey " + CBitcoinSecret(key).ToString();
CallRPC(strRPC);
// address not found before import
strRPC = "getnewaddress";
BOOST_CHECK_NO_THROW(r = CallRPC(strRPC));
string addr = r.get_str();
BOOST_CHECK_EQUAL(addr, CBitcoinAddress(pubkey.GetID()).ToString());
// address found after import
BOOST_CHECK_THROW(CallRPC(strRPC), runtime_error);
}
示例3: CalculateNestedKeyhashInputSize
// Explicit calculation which is used to test the wallet constant
// We get the same virtual size due to rounding(weight/4) for both use_max_sig values
static size_t CalculateNestedKeyhashInputSize(bool use_max_sig)
{
// Generate ephemeral valid pubkey
CKey key;
key.MakeNewKey(true);
CPubKey pubkey = key.GetPubKey();
// Generate pubkey hash
uint160 key_hash(Hash160(pubkey.begin(), pubkey.end()));
// Create inner-script to enter into keystore. Key hash can't be 0...
CScript inner_script = CScript() << OP_0 << std::vector<unsigned char>(key_hash.begin(), key_hash.end());
// Create outer P2SH script for the output
uint160 script_id(Hash160(inner_script.begin(), inner_script.end()));
CScript script_pubkey = CScript() << OP_HASH160 << std::vector<unsigned char>(script_id.begin(), script_id.end()) << OP_EQUAL;
// Add inner-script to key store and key to watchonly
CBasicKeyStore keystore;
keystore.AddCScript(inner_script);
keystore.AddKeyPubKey(key, pubkey);
// Fill in dummy signatures for fee calculation.
SignatureData sig_data;
if (!ProduceSignature(keystore, use_max_sig ? DUMMY_MAXIMUM_SIGNATURE_CREATOR : DUMMY_SIGNATURE_CREATOR, script_pubkey, sig_data)) {
// We're hand-feeding it correct arguments; shouldn't happen
assert(false);
}
CTxIn tx_in;
UpdateInput(tx_in, sig_data);
return (size_t)GetVirtualTransactionInputSize(tx_in);
}
示例4: runtime_error
std::vector<unsigned char> CKeyStore::GenerateNewKey()
{
RandAddSeedPerfmon();
CKey key;
key.MakeNewKey();
if (!AddKey(key))
throw std::runtime_error("CKeyStore::GenerateNewKey() : AddKey failed");
return key.GetPubKey();
}
示例5: GetBlockFileInfo
BOOST_FIXTURE_TEST_CASE(importmulti_rescan, TestChain100Setup)
{
auto chain = interfaces::MakeChain();
// Cap last block file size, and mine new block in a new block file.
CBlockIndex* oldTip = chainActive.Tip();
GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE;
CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
CBlockIndex* newTip = chainActive.Tip();
auto locked_chain = chain->lock();
// Prune the older block file.
PruneOneBlockFile(oldTip->GetBlockPos().nFile);
UnlinkPrunedFiles({oldTip->GetBlockPos().nFile});
// Verify importmulti RPC returns failure for a key whose creation time is
// before the missing block, and success for a key whose creation time is
// after.
{
std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>(*chain, WalletLocation(), WalletDatabase::CreateDummy());
AddWallet(wallet);
UniValue keys;
keys.setArray();
UniValue key;
key.setObject();
key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey())));
key.pushKV("timestamp", 0);
key.pushKV("internal", UniValue(true));
keys.push_back(key);
key.clear();
key.setObject();
CKey futureKey;
futureKey.MakeNewKey(true);
key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(futureKey.GetPubKey())));
key.pushKV("timestamp", newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1);
key.pushKV("internal", UniValue(true));
keys.push_back(key);
JSONRPCRequest request;
request.params.setArray();
request.params.push_back(keys);
UniValue response = importmulti(request);
BOOST_CHECK_EQUAL(response.write(),
strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation "
"timestamp %d. There was an error reading a block from time %d, which is after or within %d "
"seconds of key creation, and could contain transactions pertaining to the key. As a result, "
"transactions and coins using this key may not appear in the wallet. This error could be caused "
"by pruning or data corruption (see bitcoind log for details) and could be dealt with by "
"downloading and rescanning the relevant blocks (see -reindex and -rescan "
"options).\"}},{\"success\":true}]",
0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW));
RemoveWallet(wallet);
}
}
示例6: walletdb
CzPIVWallet::CzPIVWallet(std::string strWalletFile)
{
this->strWalletFile = strWalletFile;
CWalletDB walletdb(strWalletFile);
uint256 hashSeed;
bool fFirstRun = !walletdb.ReadCurrentSeedHash(hashSeed);
//Check for old db version of storing zpiv seed
if (fFirstRun) {
uint256 seed;
if (walletdb.ReadZPIVSeed_deprecated(seed)) {
//Update to new format, erase old
seedMaster = seed;
hashSeed = Hash(seed.begin(), seed.end());
if (pwalletMain->AddDeterministicSeed(seed)) {
if (walletdb.EraseZPIVSeed_deprecated()) {
LogPrintf("%s: Updated zPIV seed databasing\n", __func__);
fFirstRun = false;
} else {
LogPrintf("%s: failed to remove old zpiv seed\n", __func__);
}
}
}
}
//Don't try to do anything if the wallet is locked.
if (pwalletMain->IsLocked()) {
seedMaster = 0;
nCountLastUsed = 0;
this->mintPool = CMintPool();
return;
}
//First time running, generate master seed
uint256 seed;
if (fFirstRun) {
// Borrow random generator from the key class so that we don't have to worry about randomness
CKey key;
key.MakeNewKey(true);
seed = key.GetPrivKey_256();
seedMaster = seed;
LogPrintf("%s: first run of zpiv wallet detected, new seed generated. Seedhash=%s\n", __func__, Hash(seed.begin(), seed.end()).GetHex());
} else if (!pwalletMain->GetDeterministicSeed(hashSeed, seed)) {
LogPrintf("%s: failed to get deterministic seed for hashseed %s\n", __func__, hashSeed.GetHex());
return;
}
if (!SetMasterSeed(seed)) {
LogPrintf("%s: failed to save deterministic seed for hashseed %s\n", __func__, hashSeed.GetHex());
return;
}
this->mintPool = CMintPool(nCountLastUsed);
}
示例7: getnewaddress
Value getnewaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress (\"IsMiner\")\n"
"\nget a new address\n"
"\nArguments:\n"
"1. \"IsMiner\" (bool, optional) private key Is used for miner if true will create tow key ,another for miner.\n"
"\nExamples:\n"
+ HelpExampleCli("getnewaddress", "")
+ HelpExampleCli("getnewaddress", "true")
);
EnsureWalletIsUnlocked();
CKey mCkey;
mCkey.MakeNewKey();
CKey Minter;
bool IsForMiner = false;
if (params.size() == 1) {
RPCTypeCheck(params, list_of(bool_type));
Minter.MakeNewKey();
IsForMiner = params[0].get_bool();
}
CPubKey newKey = mCkey.GetPubKey();
CKeyID keyID = newKey.GetKeyID();
if (IsForMiner) {
if (!pwalletMain->AddKey(mCkey, Minter))
throw runtime_error("add key failed ");
}
else if (!pwalletMain->AddKey(mCkey)) {
throw runtime_error("add key failed ");
}
Object obj;
obj.push_back(Pair("addr", keyID.ToAddress()));
obj.push_back(Pair("minerpubkey", IsForMiner?Minter.GetPubKey().ToString(): "no" ));
return obj;
}
示例8: runtime_error
std::vector<unsigned char> CWallet::GenerateNewKey()
{
bool fCompressed = true;
RandAddSeedPerfmon();
CKey key;
key.MakeNewKey(fCompressed);
if (!AddKey(key))
throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
return key.GetPubKey();
}
示例9: GenerateNewKey
CPubKey CAccount::GenerateNewKey(CWallet& wallet, int keyChain)
{
CKey secret;
secret.MakeNewKey(true);
CPubKey pubkey = secret.GetPubKey();
assert(secret.VerifyPubKey(pubkey));
if (!wallet.AddKeyPubKey(secret, pubkey, *this, keyChain))
throw std::runtime_error("CAccount::GenerateNewKey(): AddKeyPubKey failed");
return pubkey;
}
示例10: GenerateNewKey
CPubKey CAccount::GenerateNewKey(CWallet& wallet, CKeyMetadata& metadata, int keyChain)
{
if (IsFixedKeyPool())
throw std::runtime_error(strprintf("GenerateNewKey called on a \"%sy\" witness account - this is invalid", GetAccountTypeString(m_Type).c_str()));
CKey secret;
secret.MakeNewKey(true);
CPubKey pubkey = secret.GetPubKey();
assert(secret.VerifyPubKey(pubkey));
if (!wallet.AddKeyPubKey(secret, pubkey, *this, keyChain))
throw std::runtime_error("CAccount::GenerateNewKey(): AddKeyPubKey failed");
return pubkey;
}
示例11: runtime_error
std::vector<unsigned char> CWallet::GenerateNewKey()
{
bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets
RandAddSeedPerfmon();
CKey key;
key.MakeNewKey(fCompressed);
// Compressed public keys were introduced in version 0.6.0
if (fCompressed)
SetMinVersion(FEATURE_COMPRPUBKEY);
if (!AddKey(key))
throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed");
return key.GetPubKey();
}
示例12: GenerateBeaconKeys
bool GenerateBeaconKeys(const std::string &cpid, std::string &sOutPubKey, std::string &sOutPrivKey)
{
// First Check the Index - if it already exists, use it
sOutPrivKey = GetArgument("privatekey" + cpid + GetNetSuffix(), "");
sOutPubKey = GetArgument("publickey" + cpid + GetNetSuffix(), "");
// If current keypair is not empty, but is invalid, allow the new keys to be stored, otherwise return 1: (10-25-2016)
if (!sOutPrivKey.empty() && !sOutPubKey.empty())
{
uint256 hashBlock = GetRandHash();
std::string sSignature;
std::string sError;
bool fResult;
fResult = SignBlockWithCPID(cpid, hashBlock.GetHex(), sSignature, sError, true);
if (!fResult)
LogPrintf("GenerateBeaconKeys::Failed to sign block with cpid with existing keys; generating new key pair -> %s", sError);
else
{
fResult = VerifyCPIDSignature(cpid, hashBlock.GetHex(), sSignature);
if (fResult)
{
LogPrintf("GenerateBeaconKeys::Current keypair is valid.");
return true;
}
else
LogPrintf("GenerateBeaconKeys::Signing block with CPID was successful; However Verifying CPID Sign was not; Key pair is not valid, generating new key pair");
}
}
// Generate the Keypair
CKey key;
key.MakeNewKey(false);
CPrivKey vchPrivKey = key.GetPrivKey();
sOutPrivKey = HexStr<CPrivKey::iterator>(vchPrivKey.begin(), vchPrivKey.end());
sOutPubKey = HexStr(key.GetPubKey().Raw());
return true;
}
示例13: GenerateRandomTransaction
bool TestChainForComputingMediansSetup::GenerateRandomTransaction(CTransaction& txNew)
{
CAmount amountToSend = 5000;
std::vector<CTransaction> res;
CKey key;
key.MakeNewKey(true);
CScript scriptPubKey = CScript() << ToByteVector(key.GetPubKey())
<< OP_CHECKSIG;
CBasicKeyStore keystore;
keystore.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
CTransaction utxo = coinbaseTxns[0];
coinbaseTxns.erase(coinbaseTxns.begin());
txNew.nLockTime = chainActive.Height();
txNew.vin.clear();
txNew.vout.clear();
for (int j = 0; j < nOutputs; ++j) {
CTxOut txout(amountToSend, scriptPubKey);
txNew.vout.push_back(txout);
}
//vin
CTxIn vin = CTxIn(utxo.GetHash(), 0, CScript(),
std::numeric_limits<unsigned int>::max() - 1);
txNew.vin.push_back(vin);
//previous tx's script pub key that we need to sign
CScript& scriptSigRes = txNew.vin[0].scriptSig;
CTransaction txNewConst(txNew);
ProduceSignature(TransactionSignatureCreator(&keystore, &txNewConst, 0),
utxo.vout[0].scriptPubKey, scriptSigRes);
res.push_back(txNew);
return true;
}
示例14: LOCK
BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup)
{
LOCK(cs_main);
// Cap last block file size, and mine new block in a new block file.
CBlockIndex* const nullBlock = nullptr;
CBlockIndex* oldTip = chainActive.Tip();
GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE;
CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey()));
CBlockIndex* newTip = chainActive.Tip();
// Verify ScanForWalletTransactions picks up transactions in both the old
// and new block files.
{
CWallet wallet;
LOCK(wallet.cs_wallet);
wallet.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
BOOST_CHECK_EQUAL(nullBlock, wallet.ScanForWalletTransactions(oldTip));
BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 100 * COIN);
}
// Prune the older block file.
PruneOneBlockFile(oldTip->GetBlockPos().nFile);
UnlinkPrunedFiles({oldTip->GetBlockPos().nFile});
// Verify ScanForWalletTransactions only picks transactions in the new block
// file.
{
CWallet wallet;
LOCK(wallet.cs_wallet);
wallet.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey());
BOOST_CHECK_EQUAL(oldTip, wallet.ScanForWalletTransactions(oldTip));
BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 50 * COIN);
}
// Verify importmulti RPC returns failure for a key whose creation time is
// before the missing block, and success for a key whose creation time is
// after.
{
CWallet wallet;
vpwallets.insert(vpwallets.begin(), &wallet);
UniValue keys;
keys.setArray();
UniValue key;
key.setObject();
key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey())));
key.pushKV("timestamp", 0);
key.pushKV("internal", UniValue(true));
keys.push_back(key);
key.clear();
key.setObject();
CKey futureKey;
futureKey.MakeNewKey(true);
key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(futureKey.GetPubKey())));
key.pushKV("timestamp", newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1);
key.pushKV("internal", UniValue(true));
keys.push_back(key);
JSONRPCRequest request;
request.params.setArray();
request.params.push_back(keys);
UniValue response = importmulti(request);
BOOST_CHECK_EQUAL(response.write(),
strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation "
"timestamp %d. There was an error reading a block from time %d, which is after or within %d "
"seconds of key creation, and could contain transactions pertaining to the key. As a result, "
"transactions and coins using this key may not appear in the wallet. This error could be caused "
"by pruning or data corruption (see bitcoind log for details) and could be dealt with by "
"downloading and rescanning the relevant blocks (see -reindex and -rescan "
"options).\"}},{\"success\":true}]",
0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW));
vpwallets.erase(vpwallets.begin());
}
}
示例15: on_getNewAddress_clicked
void PaperWalletDialog::on_getNewAddress_clicked()
{
// Create a new private key
CKey privKey;
privKey.MakeNewKey(true);
// Derive the public key
CPubKey pubkey = privKey.GetPubKey();
// Derive the public key hash
CBitcoinAddress pubkeyhash;
pubkeyhash.Set(pubkey.GetID());
// Create String versions of each
string myPrivKey = CBitcoinSecret(privKey).ToString();
string myPubKey = HexStr(pubkey.begin(), pubkey.end());
string myAddress = pubkeyhash.ToString();
#ifdef USE_QRCODE
// Generate the address QR code
QRcode *code = QRcode_encodeString(myAddress.c_str(), 0, QR_ECLEVEL_M, QR_MODE_8, 1);
if (!code)
{
ui->addressQRCode->setText(tr("Error encoding Address into QR Code."));
return;
}
QImage publicKeyImage = QImage(code->width, code->width, QImage::Format_ARGB32);
publicKeyImage.fill(0x000000);
unsigned char *p = code->data;
for (int y = 0; y < code->width; y++)
{
for (int x = 0; x < code->width; x++)
{
publicKeyImage.setPixel(x, y, ((*p & 1) ? 0xff000000 : 0x0));
p++;
}
}
QRcode_free(code);
// Generate the private key QR code
code = QRcode_encodeString(myPrivKey.c_str(), 0, QR_ECLEVEL_M, QR_MODE_8, 1);
if (!code)
{
ui->privateKeyQRCode->setText(tr("Error encoding private key into QR Code."));
return;
}
QImage privateKeyImage = QImage(code->width, code->width, QImage::Format_ARGB32);
privateKeyImage.fill(0x000000);
p = code->data;
for (int y = 0; y < code->width; y++)
{
for (int x = 0; x < code->width; x++)
{
privateKeyImage.setPixel(x, y, ((*p & 1) ? 0xff000000 : 0x0));
p++;
}
}
QRcode_free(code);
// Populate the QR Codes
ui->addressQRCode->setPixmap(QPixmap::fromImage(publicKeyImage).scaled(ui->addressQRCode->width(), ui->addressQRCode->height()));
ui->privateKeyQRCode->setPixmap(QPixmap::fromImage(privateKeyImage).scaled(ui->privateKeyQRCode->width(), ui->privateKeyQRCode->height()));
#endif
// Populate the Texts
ui->addressText->setText(myAddress.c_str());
ui->privateKeyText->setText(tr(myPrivKey.c_str()));
ui->publicKey->setHtml(myPubKey.c_str());
// Update the fonts to fit the height of the wallet.
// This should only really trigger the first time since the font size persists.
double paperHeight = (double) ui->paperTemplate->height();
double maxTextWidth = paperHeight * 0.99;
double minTextWidth = paperHeight * 0.95;
int pixelSizeStep = 1;
int addressTextLength = ui->addressText->fontMetrics().boundingRect(ui->addressText->text()).width();
QFont font = ui->addressText->font();
for(int i = 0; i < PAPER_WALLET_READJUST_LIMIT; i++) {
if ( addressTextLength < minTextWidth) {
font.setPixelSize(font.pixelSize() + pixelSizeStep);
ui->addressText->setFont(font);
addressTextLength = ui->addressText->fontMetrics().boundingRect(ui->addressText->text()).width();
} else {
break;
}
}
if ( addressTextLength > maxTextWidth ) {
font.setPixelSize(font.pixelSize() - pixelSizeStep);
ui->addressText->setFont(font);
addressTextLength = ui->addressText->fontMetrics().boundingRect(ui->addressText->text()).width();
}
int privateKeyTextLength = ui->privateKeyText->fontMetrics().boundingRect(ui->privateKeyText->text()).width();
font = ui->privateKeyText->font();
for(int i = 0; i < PAPER_WALLET_READJUST_LIMIT; i++) {
//.........这里部分代码省略.........