本文整理汇总了C++中CKey::IsValid方法的典型用法代码示例。如果您正苦于以下问题:C++ CKey::IsValid方法的具体用法?C++ CKey::IsValid怎么用?C++ CKey::IsValid使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类CKey
的用法示例。
在下文中一共展示了CKey::IsValid方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: ParseCertificate
static X509* ParseCertificate(FILE* file, const bool fChainAdmin, const string& strPassword)
{
OpenSSL_add_all_algorithms(); // needed to load encrypted private keys
EVP_PKEY *privkey = EVP_PKEY_new();
if (!PEM_read_PrivateKey(file, &privkey, NULL, strPassword.length() ? (char *)strPassword.c_str() : NULL)) {
fclose(file);
LogPrintf("ERROR: could not open certificate file.\n");
return NULL;
}
fclose(file);
const EC_KEY* eckey = EVP_PKEY_get1_EC_KEY(privkey);
if (!EC_KEY_check_key(eckey)) {
LogPrintf("ERROR: invalid key supplied\n");
return NULL;
}
const BIGNUM *bnPrivKey = EC_KEY_get0_private_key(eckey);
unsigned char buf[256];
size_t sKeyLen = BN_bn2bin(bnPrivKey, buf);
const vector<unsigned char> data(buf, buf + sKeyLen);
if (fChainAdmin)
adminPrivKey.Set(data.begin(), data.end(), false);
else
cvnPrivKey.Set(data.begin(), data.end(), false);
if ((fChainAdmin && !adminPrivKey.IsValid()) || (!fChainAdmin && !cvnPrivKey.IsValid())) {
LogPrintf("ERROR: could not validate supplied %s key\n", fChainAdmin ? "admin" : "cvn");
return NULL;
}
BIO *bioCert = BIO_new(BIO_s_file());
boost::filesystem::path certFile = GetDataDir() / (fChainAdmin ? GetArg("-admincertfile", "admin.pem") : GetArg("-cvncertfile", "cvn.pem"));
if (!BIO_read_filename(bioCert, certFile.string().c_str())) {
LogPrintf("ERROR: cert file not found: %s, is -%scertfile set correctly?\n", certFile, fChainAdmin ? "admin" : "cvn");
return NULL;
}
X509 *x509Cert = PEM_read_bio_X509(bioCert, NULL, 0, NULL);
BIO_free(bioCert);
return x509Cert;
}
示例2: SetCheckpointPrivKey
bool SetCheckpointPrivKey(std::string strPrivKey)
{
// do nothing for testnet
// if (fTestNet)
// return true;
// Test signing a sync-checkpoint with genesis block
CSyncCheckpoint checkpoint;
checkpoint.hashCheckpoint = fTestNet ? hashGenesisBlockTestNet: hashGenesisBlock;
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
sMsg << (CUnsignedSyncCheckpoint)checkpoint;
checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
std::vector<unsigned char> vchPrivKey = ParseHex(strPrivKey);
CKey key;
// if key is not correct openssl may crash
key.Set(vchPrivKey.begin(), vchPrivKey.end(), false);
if (!key.IsValid())
return error("SetCheckpointPrivKey: failed to set private key.");
if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
return error("SetCheckpointPrivKey: failed to test sign.");
// Test signing successful, proceed
CSyncCheckpoint::strMasterPrivKey = strPrivKey;
printf("SetCheckpointPrivKey: successfully set private key.");
return true;
}
示例3: SetKey
void CTransactcoinSecret::SetKey(const CKey& vchSecret)
{
assert(vchSecret.IsValid());
SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
if (vchSecret.IsCompressed())
vchData.push_back(1);
}
示例4: SignAndSave
void SignAndSave(CAlert alert, const std::string filename) {
//serialze alert message
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
sMsg << (CUnsignedAlert)alert;
alert.vchMsg.reserve(sMsg.size());
for(size_t i=0; i<sMsg.size(); i++) {
alert.vchMsg.push_back(sMsg[i]);
}
//a dummy secret key with the public key
//0469204F0E1800E16C1F85176BDC27A245F09987DB71A1EF5C4BD48A42F9AFD1D74F21469488DB552B594AC29CE667AD60DAAD0FFBCE03FB0C2AC49FFB07B36DC5
//set to match the mainnet vAlertPubKey from chainparams.cpp
const std::vector<unsigned char> secretKey = ParseHex("1A4976EE6174D80B8B3FF5E9B9C6E638CABFA9A5975557FEA967BC089A5584EE");
CKey secret;
secret.Set(secretKey.begin(), secretKey.end(), false);
assert(secret.IsValid());
//sign alert
secret.Sign(alert.GetHash(), alert.vchSig);
assert(alert.CheckSignature());
//serialize alert
CDataStream ss(SER_DISK, CLIENT_VERSION);
ss << alert;
//write alert
std::ofstream fs;
fs.open(filename.c_str(), std::ios::out | std::ios::app | std::ios::binary);
fs.write((char*)&ss[0], ss.size());
fs.close();
}
示例5: SetKey
void CBitcoinSecret::SetKey(const CKey& vchSecret,
std::vector<unsigned char> prefix) {
assert(vchSecret.IsValid());
SetData(prefix, vchSecret.begin(), vchSecret.size());
if (vchSecret.IsCompressed())
vchData.push_back(1);
}
示例6: EncodeSecret
std::string EncodeSecret(const CKey& key)
{
assert(key.IsValid());
std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::SECRET_KEY);
data.insert(data.end(), key.begin(), key.end());
if (key.IsCompressed()) {
data.push_back(1);
}
std::string ret = EncodeBase58Check(data);
memory_cleanse(data.data(), data.size());
return ret;
}
示例7: ctx
void Bip38ToolDialog::on_importAddressButton_DEC_clicked()
{
WalletModel::UnlockContext ctx(model->requestUnlock(true));
if (!ctx.isValid()) {
ui->statusLabel_DEC->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_DEC->setText(tr("Wallet unlock was cancelled."));
return;
}
CPubKey pubkey = key.GetPubKey();
if (!IsValidDestinationString(ui->addressOut_DEC->text().toStdString())) {
ui->statusLabel_DEC->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_DEC->setText(tr("Data Not Valid.") + QString(" ") + tr("Please try again."));
return;
}
CTxDestination address = DecodeDestination(ui->addressOut_DEC->text().toStdString());
if (!key.IsValid() || EncodeDestination(pubkey.GetID()) != EncodeDestination(address))
{
CKeyID vchAddress = pubkey.GetID();
ui->statusLabel_DEC->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_DEC->setText(tr("Please wait while key is imported"));
pwalletMain->MarkDirty();
pwalletMain->SetAddressBook(vchAddress, "", "receive");
// Don't throw error in case a key is already there
if (pwalletMain->HaveKey(vchAddress)) {
ui->statusLabel_DEC->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_DEC->setText(tr("Key Already Held By Wallet"));
return;
}
pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1;
if (!pwalletMain->AddKeyPubKey(key, pubkey)) {
ui->statusLabel_DEC->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_DEC->setText(tr("Error Adding Key To Wallet"));
return;
}
// whenever a key is imported, we need to scan the whole chain
pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value'
pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true);
}
ui->statusLabel_DEC->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_DEC->setText(tr("Successfully Added Private Key To Wallet"));
}
示例8: LoadBuffer
bool CWalletBackup::LoadBuffer(CDataStream& ssBuffer)
{
try
{
while(!ssBuffer.empty())
{
string strType;
ssBuffer >> strType;
if (strType == "key")
{
vector<unsigned char> vchPubKey;
CPrivKey pkey;
ssBuffer >> vchPubKey >> pkey;
CKey key;
key.SetPubKey(vchPubKey);
key.SetPrivKey(pkey);
if (key.GetPubKey() != vchPubKey || !key.IsValid()
|| !AddKey(key))
{
return false;
}
}
else if (strType == "wkey")
{
vector<unsigned char> vchPubKey;
CWalletKey wkey;
ssBuffer >> vchPubKey >> wkey;
CKey key;
key.SetPubKey(vchPubKey);
key.SetPrivKey(wkey.vchPrivKey);
if (key.GetPubKey() != vchPubKey || !key.IsValid()
|| !AddKey(key))
{
return false;
}
}
示例9: importprivkey
Value importprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"importprivkey <dokdocoinprivkey> [label] [rescan=true]\n"
"Adds a private key (as returned by dumpprivkey) to your wallet.");
EnsureWalletIsUnlocked();
string strSecret = params[0].get_str();
string strLabel = "";
if (params.size() > 1)
strLabel = params[1].get_str();
// Whether to perform rescan after import
bool fRescan = true;
if (params.size() > 2)
fRescan = params[2].get_bool();
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strSecret);
if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
CKey key = vchSecret.GetKey();
CPubKey pubkey = key.GetPubKey();
CKeyID vchAddress = pubkey.GetID();
if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
{
LOCK2(cs_main, pwalletMain->cs_wallet);
pwalletMain->MarkDirty();
pwalletMain->SetAddressBookName(vchAddress, strLabel);
if (!pwalletMain->AddKeyPubKey(key, pubkey))
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
if (fRescan) {
pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true);
pwalletMain->ReacceptWalletTransactions();
}
}
return Value::null;
}
示例10: signmessagewithprivkey
static UniValue signmessagewithprivkey(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 2)
throw std::runtime_error(
RPCHelpMan{"signmessagewithprivkey",
"\nSign a message with the private key of an address\n",
{
{"privkey", RPCArg::Type::STR, RPCArg::Optional::NO, "The private key to sign the message with."},
{"message", RPCArg::Type::STR, RPCArg::Optional::NO, "The message to create a signature of."},
},
RPCResult{
"\"signature\" (string) The signature of the message encoded in base 64\n"
},
RPCExamples{
"\nCreate the signature\n"
+ HelpExampleCli("signmessagewithprivkey", "\"privkey\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("signmessagewithprivkey", "\"privkey\", \"my message\"")
},
}.ToString());
std::string strPrivkey = request.params[0].get_str();
std::string strMessage = request.params[1].get_str();
CKey key = DecodeSecret(strPrivkey);
if (!key.IsValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
}
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
std::vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(vchSig.data(), vchSig.size());
}
示例11: GetKey
bool CAccountHD::GetKey(const CKeyID& keyID, CKey& key) const
{
assert(!m_readOnly);
assert(IsHD());
// Witness keys are a special case.
// They are stored instead of generated on demand (so that they work in encrypted wallets)
if (IsPoW2Witness())
{
if (internalKeyStore.GetKey(keyID, key))
{
// But skip it if it is an empty key... (Which can happen by design)
// Technical: Witness keystore is filled with "public/empty" pairs as the public keys are created and then populated on demand with "public/witness" keys only when they are needed/generated (first use)
if (key.IsValid())
return true;
}
}
if (IsLocked())
return false;
int64_t nKeyIndex = -1;
CExtKey privKey;
if (externalKeyStore.GetKey(keyID, nKeyIndex))
{
primaryChainKeyPriv.Derive(privKey, nKeyIndex);
if(privKey.Neuter().pubkey.GetID() != keyID)
assert(0);
key = privKey.key;
return true;
}
if (internalKeyStore.GetKey(keyID, nKeyIndex))
{
changeChainKeyPriv.Derive(privKey, nKeyIndex);
if(privKey.Neuter().pubkey.GetID() != keyID)
assert(0);
key = privKey.key;
return true;
}
return false;
}
示例12: signmessagewithprivkey
UniValue signmessagewithprivkey(const JSONRPCRequest& request)
{
if (request.fHelp || request.params.size() != 2)
throw std::runtime_error(
"signmessagewithprivkey \"privkey\" \"message\"\n"
"\nSign a message with the private key of an address\n"
"\nArguments:\n"
"1. \"privkey\" (string, required) The private key to sign the message with.\n"
"2. \"message\" (string, required) The message to create a signature of.\n"
"\nResult:\n"
"\"signature\" (string) The signature of the message encoded in base 64\n"
"\nExamples:\n"
"\nCreate the signature\n"
+ HelpExampleCli("signmessagewithprivkey", "\"privkey\" \"my message\"") +
"\nVerify the signature\n"
+ HelpExampleCli("verifymessage", "\"1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XX\" \"signature\" \"my message\"") +
"\nAs json rpc\n"
+ HelpExampleRpc("signmessagewithprivkey", "\"privkey\", \"my message\"")
);
std::string strPrivkey = request.params[0].get_str();
std::string strMessage = request.params[1].get_str();
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strPrivkey);
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
if (!key.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << strMessage;
std::vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Sign failed");
return EncodeBase64(&vchSig[0], vchSig.size());
}
示例13: SendSyncCheckpoint
bool SendSyncCheckpoint(uint256 hashCheckpoint)
{
CSyncCheckpoint checkpoint;
checkpoint.hashCheckpoint = hashCheckpoint;
CDataStream sMsg(SER_NETWORK, PROTOCOL_VERSION);
sMsg << (CUnsignedSyncCheckpoint)checkpoint;
checkpoint.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
if (CSyncCheckpoint::strMasterPrivKey.empty())
return error("SendSyncCheckpoint: Checkpoint master private key unavailable.");
std::vector<unsigned char> vchPrivKey = ParseHex(CSyncCheckpoint::strMasterPrivKey);
CKey key;
// if key is not correct openssl may crash
key.Set(vchPrivKey.begin(), vchPrivKey.end(), false);
if (!key.IsValid())
return error("SendSyncCheckpoint: failed to set private key.");
if (!key.Sign(Hash(checkpoint.vchMsg.begin(), checkpoint.vchMsg.end()), checkpoint.vchSig))
return error("SendSyncCheckpoint: Unable to sign checkpoint, check private key?");
if(!checkpoint.ProcessSyncCheckpoint(NULL))
{
printf("WARNING: SendSyncCheckpoint: Failed to process checkpoint.\n");
return false;
}
printf("SendSyncCheckpoint: about to relay checkpoint.\n");
// Relay checkpoint
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
checkpoint.RelayTo(pnode);
}
return true;
}
示例14: signrawtransaction
//.........这里部分代码省略.........
CMutableTransaction mtx;
if (!DecodeHexTx(mtx, request.params[0].get_str(), true))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
// Fetch previous transactions (inputs):
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache &viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(&viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
for (const CTxIn& txin : mtx.vin) {
view.AccessCoin(txin.prevout); // Load entries from viewChain into view; can fail.
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (!request.params[2].isNull()) {
fGivenKeys = true;
UniValue keys = request.params[2].get_array();
for (unsigned int idx = 0; idx < keys.size(); idx++) {
UniValue k = keys[idx];
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
if (!key.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
tempKeystore.AddKey(key);
}
}
#ifdef ENABLE_WALLET
else if (pwallet) {
EnsureWalletIsUnlocked(pwallet);
}
#endif
// Add previous txouts given in the RPC call:
if (!request.params[1].isNull()) {
UniValue prevTxs = request.params[1].get_array();
for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
const UniValue& p = prevTxs[idx];
if (!p.isObject())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
UniValue prevOut = p.get_obj();
RPCTypeCheckObj(prevOut,
{
{"txid", UniValueType(UniValue::VSTR)},
{"vout", UniValueType(UniValue::VNUM)},
{"scriptPubKey", UniValueType(UniValue::VSTR)},
});
uint256 txid = ParseHashO(prevOut, "txid");
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");
示例15: signrawtransaction
//.........这里部分代码省略.........
// starts as a clone of the rawtx:
CMutableTransaction mergedTx(txVariants[0]);
// Fetch previous transactions (inputs):
CCoinsView viewDummy;
CCoinsViewCache view(&viewDummy);
{
LOCK(mempool.cs);
CCoinsViewCache &viewChain = *pcoinsTip;
CCoinsViewMemPool viewMempool(&viewChain, mempool);
view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view
BOOST_FOREACH(const CTxIn& txin, mergedTx.vin) {
const uint256& prevHash = txin.prevout.hash;
CCoins coins;
view.AccessCoins(prevHash); // this is certainly allowed to fail
}
view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long
}
bool fGivenKeys = false;
CBasicKeyStore tempKeystore;
if (params.size() > 2 && !params[2].isNull()) {
fGivenKeys = true;
UniValue keys = params[2].get_array();
for (unsigned int idx = 0; idx < keys.size(); idx++) {
UniValue k = keys[idx];
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(k.get_str());
if (!fGood)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key");
CKey key = vchSecret.GetKey();
if (!key.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
tempKeystore.AddKey(key);
}
}
#ifdef ENABLE_WALLET
else if (pwalletMain)
EnsureWalletIsUnlocked();
#endif
// Add previous txouts given in the RPC call:
if (params.size() > 1 && !params[1].isNull()) {
UniValue prevTxs = params[1].get_array();
for (unsigned int idx = 0; idx < prevTxs.size(); idx++) {
const UniValue& p = prevTxs[idx];
if (!p.isObject())
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}");
UniValue prevOut = p.get_obj();
RPCTypeCheckObj(prevOut,
{
{"txid", UniValueType(UniValue::VSTR)},
{"vout", UniValueType(UniValue::VNUM)},
{"scriptPubKey", UniValueType(UniValue::VSTR)},
});
uint256 txid = ParseHashO(prevOut, "txid");
int nOut = find_value(prevOut, "vout").get_int();
if (nOut < 0)
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive");