示例#1
0
    void testKeySize ()
    {
        testcase ("Key Sizes");

        RsaSha256 f1;
        BEAST_EXPECT (!f1.sign (longKey, makeSlice (knownMessage)));

        RsaSha256 f2;
        BEAST_EXPECT (!f2.sign (shortKey, makeSlice (knownMessage)));
    }
示例#2
0
bool LevelDBDatabase::put(const LevelDBSlice& key, const Vector<char>& value)
{
    leveldb::WriteOptions writeOptions;
    writeOptions.sync = true;

    const leveldb::Status s = m_db->Put(writeOptions, makeSlice(key), makeSlice(value));
    if (s.ok())
        return true;
    LOG_ERROR("LevelDB put failed: %s", s.ToString().c_str());
    return false;
}
示例#3
0
NotTEC
Transactor::checkSingleSign (PreclaimContext const& ctx)
{
    auto const id = ctx.tx.getAccountID(sfAccount);

    auto const sle = ctx.view.read(
        keylet::account(id));
    auto const hasAuthKey     = sle->isFieldPresent (sfRegularKey);

    // Consistency: Check signature & verify the transaction's signing
    // public key is authorized for signing.
    auto const spk = ctx.tx.getSigningPubKey();
    if (!publicKeyType (makeSlice (spk)))
    {
        JLOG(ctx.j.trace()) <<
            "checkSingleSign: signing public key type is unknown";
        return tefBAD_AUTH; // FIXME: should be better error!
    }

    auto const pkAccount = calcAccountID (
        PublicKey (makeSlice (spk)));

    if (pkAccount == id)
    {
        // Authorized to continue.
        if (sle->isFlag(lsfDisableMaster))
            return tefMASTER_DISABLED;
    }
    else if (hasAuthKey &&
        (pkAccount == sle->getAccountID (sfRegularKey)))
    {
        // Authorized to continue.
    }
    else if (hasAuthKey)
    {
        JLOG(ctx.j.trace()) <<
            "checkSingleSign: Not authorized to use account.";
        return tefBAD_AUTH;
    }
    else
    {
        JLOG(ctx.j.trace()) <<
            "checkSingleSign: Not authorized to use account.";
        return tefBAD_AUTH_MASTER;
    }

    return tesSUCCESS;
}
示例#4
0
/** Performs early sanity checks on the account and fee fields */
NotTEC
preflight1 (PreflightContext const& ctx)
{
    auto const ret = preflight0(ctx);
    if (!isTesSuccess(ret))
        return ret;

    auto const id = ctx.tx.getAccountID(sfAccount);
    if (id == beast::zero)
    {
        JLOG(ctx.j.warn()) << "preflight1: bad account id";
        return temBAD_SRC_ACCOUNT;
    }

    // No point in going any further if the transaction fee is malformed.
    auto const fee = ctx.tx.getFieldAmount (sfFee);
    if (!fee.native () || fee.negative () || !isLegalAmount (fee.xrp ()))
    {
        JLOG(ctx.j.debug()) << "preflight1: invalid fee";
        return temBAD_FEE;
    }

    auto const spk = ctx.tx.getSigningPubKey();

    if (!spk.empty () && !publicKeyType (makeSlice (spk)))
    {
        JLOG(ctx.j.debug()) << "preflight1: invalid signing key";
        return temBAD_SIGNATURE;
    }

    return tesSUCCESS;
}
示例#5
0
    /** We got some data for a ledger we are no longer acquiring Since we paid
        the price to receive it, we might as well stash it in case we need it.

        Nodes are received in wire format and must be stashed/hashed in prefix
        format
    */
    void gotStaleData (std::shared_ptr<protocol::TMLedgerData> packet_ptr) override
    {
        const uint256 uZero;
        Serializer s;
        try
        {
            for (int i = 0; i < packet_ptr->nodes ().size (); ++i)
            {
                auto const& node = packet_ptr->nodes (i);

                if (!node.has_nodeid () || !node.has_nodedata ())
                    return;

                auto id_string = node.nodeid();
                auto newNode = SHAMapAbstractNode::make(
                    makeSlice(node.nodedata()),
                    0, snfWIRE, SHAMapHash{uZero}, false, app_.journal ("SHAMapNodeID"),
                    SHAMapNodeID(id_string.data(), id_string.size()));

                if (!newNode)
                    return;

                s.erase();
                newNode->addRaw(s, snfPREFIX);

                auto blob = std::make_shared<Blob> (s.begin(), s.end());

                app_.getLedgerMaster().addFetchPack(
                    newNode->getNodeHash().as_uint256(), blob);
            }
        }
        catch (std::exception const&)
        {
        }
    }
示例#6
0
static bool parseNotExpression(MemoryStack* stack, LexerCarriage* carriage, Array<SyntaxError>* errors, ASTNode* result)
{
    if (carriage->topToken.type == TOK_NOT)
    {
        parseNextToken(carriage);

        result->nodeType = AST_FUNCTION_CALL;
        result->functionCall.identifier = makeSlice("opNot");
        result->functionCall.arguments = {};

        ASTNode node;
        if (parseAddSubExpression(stack, carriage, errors, &node))
        {
            *pushElement(&result->functionCall.arguments, stack) = node;

            return true;
        }
        else
            return false;
    }
    else
    {
        return parseAddSubExpression(stack, carriage, errors, result);
    }
}
示例#7
0
boost::optional<PublicKey>
parseBase58 (TokenType type, std::string const& s)
{
    auto const result = decodeBase58Token(s, type);
    auto const pks = makeSlice(result);
    if (!publicKeyType(pks))
        return boost::none;
    return PublicKey(pks);
}
示例#8
0
static void makeFunctionCallNode(ASTNode* result, MemoryStack* stack, char* name, ASTNode left, ASTNode right, int lineNumber = 0)
{
    result->nodeType = AST_FUNCTION_CALL;
    result->functionCall.lineNumber = lineNumber;
    result->functionCall.identifier = makeSlice(name);
    result->functionCall.arguments = {};

    *pushElement(&result->functionCall.arguments, stack) = left;
    *pushElement(&result->functionCall.arguments, stack) = right;
}
示例#9
0
static bool calcFunctionIdentifier(Scope* mainScope, Scope* tmpScope, MemoryStack* stack, RuntimeError* error, ASTNode* node, FunctionIdentifier* result)
{
    assert(node->nodeType == AST_FUNCTION_CALL);

    result->name = node->functionCall.identifier;
    result->arguments = {};

    bool stillWorking = true;

    ListIterator<ASTNode> args = makeIterator(&node->functionCall.arguments);
    while (stillWorking && hasNext(&args))
    {
        ASTNode* node = getNext(&args);
        Argument* arg = scopePushToList<Argument>(tmpScope, stack, &result->arguments);

        arg->identifier = {};

        if (node->nodeType == AST_EXPRESSION_CONSTANT)
        {
            arg->type = Type{ getTypeDefinition(mainScope, makeSlice("s32")), false };
        }
        else if (node->nodeType == AST_EXPRESSION_IDENTIFIER || node->nodeType == AST_EXPRESSION_DOT)
        {
            Value value;
            if (getValue(mainScope, node, error, &value))
            {
                arg->type = value.type;
            }
            else
            {
                stillWorking = false;
            }
        }
        else if (node->nodeType == AST_FUNCTION_CALL)
        {
            FunctionIdentifier identifier = { };
            if (calcFunctionIdentifier(mainScope, tmpScope, stack, error, node, &identifier))
            {
                Function* func = getFunction(mainScope, identifier);
                if (func)
                    arg->type = func->returnType;
                else
                {
                    *error = RuntimeError{ RET_UNDEFINED_FUNCTION, identifier.name, node->functionCall.lineNumber };
                    stillWorking = false;
                }
            }
            else
                stillWorking = false;
        }
    }

    return stillWorking;
}
示例#10
0
boost::optional<PublicKey>
parseBase58 (TokenType type, std::string const& s)
{
    auto const result =
        decodeBase58Token(s, type);
    if (result.empty())
        return boost::none;
    if (result.size() != 33)
        return boost::none;
    return PublicKey(makeSlice(result));
}
示例#11
0
LexerCarriage initCarriage(char* text)
{
    LexerCarriage result;
    result.lexingText = makeSlice(text);
    result.posInText = 0;
    result.currentLineNumber = 1;

    parseNextToken(&result);

    return result;
}
示例#12
0
static void convertToKeywordIfItIs(StringSlice slice, Token* result)
{
    for (int i = 0; i < ArrayCount(keywords); ++i)
    {
        if (slice == makeSlice(keywords[i]))
        {
            result->type = (TokenType)(KEYWORDS_STARTS_AT + i);
            break;
        }
    }
}
示例#13
0
文件: Seed.cpp 项目: bachase/rippled
boost::optional<Seed>
parseBase58 (std::string const& s)
{
    auto const result = decodeBase58Token(
         s, TokenType::TOKEN_FAMILY_SEED);
    if (result.empty())
        return boost::none;
    if (result.size() != 16)
        return boost::none;
    return Seed(makeSlice(result));
}
示例#14
0
文件: Seed.cpp 项目: bachase/rippled
Seed
randomSeed()
{
    std::array <std::uint8_t, 16> buffer;
    beast::rngfill (
        buffer.data(),
        buffer.size(),
        crypto_prng());
    Seed seed (makeSlice (buffer));
    beast::secure_erase(buffer.data(), buffer.size());
    return seed;
}
示例#15
0
boost::optional<Manifest>
Manifest::make_Manifest (std::string s)
{
    try
    {
        STObject st (sfGeneric);
        SerialIter sit (s.data (), s.size ());
        st.set (sit);
        auto const pk = st.getFieldVL (sfPublicKey);
        if (! publicKeyType (makeSlice(pk)))
            return boost::none;

        auto const opt_seq = get (st, sfSequence);
        auto const opt_msig = get (st, sfMasterSignature);
        if (!opt_seq || !opt_msig)
            return boost::none;

        // Signing key and signature are not required for
        // master key revocations
        if (*opt_seq != std::numeric_limits<std::uint32_t>::max ())
        {
            auto const spk = st.getFieldVL (sfSigningPubKey);
            if (! publicKeyType (makeSlice(spk)))
                return boost::none;
            auto const opt_sig = get (st, sfSignature);
            if (! opt_sig)
                return boost::none;

            return Manifest (std::move (s), PublicKey (makeSlice(pk)),
                PublicKey (makeSlice(spk)), *opt_seq);
        }

        return Manifest (std::move (s), PublicKey (makeSlice(pk)),
            PublicKey(), *opt_seq);
    }
    catch (std::exception const&)
    {
        return boost::none;
    }
}
示例#16
0
bool LedgerProposal::checkSign (std::string const& signature) const
{
    auto const valid = mPublicKey.verifyNodePublic(
        getSigningHash(), signature, ECDSA::not_strict);

    HashStream h;
    hash_append(h);
    assert(valid == (publicKey_.verify(
        Slice(h.data(), h.size()),
            makeSlice(signature), false)));

    return valid;
}
示例#17
0
bool LevelDBDatabase::remove(const LevelDBSlice& key)
{
    leveldb::WriteOptions writeOptions;
    writeOptions.sync = true;

    const leveldb::Status s = m_db->Delete(writeOptions, makeSlice(key));
    if (s.ok())
        return true;
    if (s.IsNotFound())
        return false;
    LOG_ERROR("LevelDB remove failed: %s", s.ToString().c_str());
    return false;
}
示例#18
0
std::uint64_t
SetRegularKey::calculateBaseFee (
    PreclaimContext const& ctx)
{
    auto const id = ctx.tx.getAccountID(sfAccount);
    auto const spk = ctx.tx.getSigningPubKey();

    if (publicKeyType (makeSlice (spk)))
    {
        if (calcAccountID(PublicKey (makeSlice(spk))) == id)
        {
            auto const sle = ctx.view.read(keylet::account(id));

            if (sle && (! (sle->getFlags () & lsfPasswordSpent)))
            {
                // flag is armed and they signed with the right account
                return 0;
            }
        }
    }

    return Transactor::calculateBaseFee (ctx);
}
示例#19
0
void STTx::sign (
    PublicKey const& publicKey,
    SecretKey const& secretKey)
{
    auto const data = getSigningData (*this);

    auto const sig = ripple::sign (
        publicKey,
        secretKey,
        makeSlice(data));

    setFieldVL (sfTxnSignature, sig);
    tid_ = getHash(HashPrefix::transactionID);
}
示例#20
0
STValidation::STValidation (SerialIter& sit, bool checkSignature)
    : STObject (getFormat (), sit, sfValidation)
{
    mNodeID = calcNodeID(
        PublicKey(makeSlice (getFieldVL (sfSigningPubKey))));
    assert (mNodeID.isNonZero ());

    if  (checkSignature && !isValid ())
    {
        JLOG (debugLog().error())
            << "Invalid validation" << getJson (0);
        Throw<std::runtime_error> ("Invalid validation");
    }
}
示例#21
0
std::pair<bool, std::string> STTx::checkSingleSign () const
{
    // We don't allow both a non-empty sfSigningPubKey and an sfSigners.
    // That would allow the transaction to be signed two ways.  So if both
    // fields are present the signature is invalid.
    if (isFieldPresent (sfSigners))
        return {false, "Cannot both single- and multi-sign."};

    bool validSig = false;
    try
    {
        bool const fullyCanonical = (getFlags() & tfFullyCanonicalSig);
        auto const spk = getFieldVL (sfSigningPubKey);

        if (publicKeyType (makeSlice(spk)))
        {
            Blob const signature = getFieldVL (sfTxnSignature);
            Blob const data = getSigningData (*this);

            validSig = verify (
                PublicKey (makeSlice(spk)),
                makeSlice(data),
                makeSlice(signature),
                fullyCanonical);
        }
    }
    catch (std::exception const&)
    {
        // Assume it was a signature failure.
        validSig = false;
    }
    if (validSig == false)
        return {false, "Invalid signature."};

    return {true, ""};
}
示例#22
0
static void loadExternals(Scope* scope, MemoryStack* stack, ExternalFunctions externals)
{
    for (int i = 0; i < externals.count; ++i)
    {
        Function* func = scopePushToList(scope, stack, &scope->functions);

        func->type = FT_EXTERNAL;
        func->identifier.name = makeSlice(externals.externals[i].name);
        func->identifier.arguments = {};
        func->func = externals.externals[i].func;

        if (strcmp(externals.externals[i].returnType, "void") == 0)
            func->returnType = {};
        else
            func->returnType = Type{ getTypeDefinition(scope, makeSlice(externals.externals[i].returnType)), false };

        for (int argIndex = 0; argIndex < externals.externals[i].argumentsCount; ++argIndex)
        {
            Argument* arg = scopePushToList(scope, stack, &func->identifier.arguments);
            arg->identifier = makeSlice(externals.externals[i].arguments[argIndex].identifier);
            arg->type = Type{ getTypeDefinition(scope, makeSlice(externals.externals[i].arguments[argIndex].typeIdentifier)), false };
        }
    }
}
示例#23
0
bool LevelDBDatabase::get(const LevelDBSlice& key, Vector<char>& value)
{
    std::string result;
    leveldb::ReadOptions readOptions;
    readOptions.verify_checksums = true; // FIXME: Disable this if the performance impact is too great.

    const leveldb::Status s = m_db->Get(readOptions, makeSlice(key), &result);
    if (s.ok()) {
        value = makeVector(result);
        return true;
    }
    if (s.IsNotFound())
        return false;
    LOG_ERROR("LevelDB get failed: %s", s.ToString().c_str());
    return false;
}
示例#24
0
static THREAD_RETURN fecMain(void *args0)
{
    sender_state_t sendst = (sender_state_t) args0;

    slice_t slice;
    int sliceNo = 0;

    while(1) {
        /* consume free slice */
        slice = makeSlice(sendst, sliceNo++);
        /* do the fec calculation here */
        fec_encode_all_stripes(sendst,slice);
        pc_produce(sendst->fec_data_pc, 1);
    }
    return 0;
}
示例#25
0
bool STValidation::isValid (uint256 const& signingHash) const
{
    try
    {
        return verifyDigest (getSignerPublic(),
            signingHash,
            makeSlice(getFieldVL (sfSignature)),
            getFlags () & vfFullyCanonicalSig);
    }
    catch (std::exception const&)
    {
        JLOG (debugLog().error())
            << "Exception validating validation";
        return false;
    }
}
示例#26
0
TxMeta::TxMeta (uint256 const& txid,
    std::uint32_t ledger, T const& data, beast::Journal j, CtorHelper)
    : mTransactionID (txid)
    , mLedger (ledger)
    , mNodes (sfAffectedNodes, 32)
    , j_ (j)
{
    SerialIter sit (makeSlice(data));

    STObject obj(sit, sfMetadata);
    mResult = obj.getFieldU8 (sfTransactionResult);
    mIndex = obj.getFieldU32 (sfTransactionIndex);
    mNodes = * dynamic_cast<STArray*> (&obj.getField (sfAffectedNodes));

    if (obj.isFieldPresent (sfDeliveredAmount))
        setDeliveredAmount (obj.getFieldAmount (sfDeliveredAmount));
}
示例#27
0
Transaction::pointer Transaction::transactionFromSQL (
    boost::optional<std::uint64_t> const& ledgerSeq,
    boost::optional<std::string> const& status,
    Blob const& rawTxn,
    Validate validate)
{
    std::uint32_t const inLedger =
        rangeCheckedCast<std::uint32_t>(ledgerSeq.value_or (0));

    SerialIter it (makeSlice(rawTxn));
    auto txn = std::make_shared<STTx> (it);
    std::string reason;
    auto tr = std::make_shared<Transaction> (txn, validate, reason);

    tr->setStatus (sqlTransactionStatus (status));
    tr->setLedger (inLedger);
    return tr;
}
示例#28
0
static void scalarS32FuncsHandler(StringSlice name, LinkedList<Variable>* arguments, Value* result)
{
    int res;
    if (name == makeSlice("opAdd"))
        res = *(int*)getValueFunc(arguments, "a") + *(int*)getValueFunc(arguments, "b");
    else if (name == makeSlice("opSub"))
        res = *(int*)getValueFunc(arguments, "a") - *(int*)getValueFunc(arguments, "b");
    else if (name == makeSlice("opLess"))
        res = *(int*)getValueFunc(arguments, "a") < *(int*)getValueFunc(arguments, "b");
    else if (name == makeSlice("opGreater"))
        res = *(int*)getValueFunc(arguments, "a") > *(int*)getValueFunc(arguments, "b");
    else if (name == makeSlice("opEqualsOrLess"))
        res = *(int*)getValueFunc(arguments, "a") <= *(int*)getValueFunc(arguments, "b");
    else if (name == makeSlice("opEqualsOrGreater"))
        res = *(int*)getValueFunc(arguments, "a") >= *(int*)getValueFunc(arguments, "b");
    else if (name == makeSlice("opEquals"))
        res = *(int*)getValueFunc(arguments, "a") == *(int*)getValueFunc(arguments, "b");
    else if (name == makeSlice("opNot"))
        res = !(*(int*)getValueFunc(arguments, "a") != 0);

    memcpy(result->memory, &res, 4);
}
示例#29
0
bool LevelDBDatabase::safeGet(const LevelDBSlice& key, Vector<char>& value, bool& found, const LevelDBSnapshot* snapshot)
{
    found = false;
    std::string result;
    leveldb::ReadOptions readOptions;
    readOptions.verify_checksums = true; // FIXME: Disable this if the performance impact is too great.
    readOptions.snapshot = snapshot ? snapshot->m_snapshot : 0;

    const leveldb::Status s = m_db->Get(readOptions, makeSlice(key), &result);
    if (s.ok()) {
        found = true;
        value.clear();
        value.append(result.c_str(), result.length());
        return true;
    }
    if (s.IsNotFound())
        return true;
    LOG_ERROR("LevelDB get failed: %s", s.ToString().c_str());
    return false;
}
示例#30
0
// {
//   public_key: <public_key>
//   channel_id: 256-bit channel id
//   drops: 64-bit uint (as string)
//   signature: signature to verify
// }
Json::Value doChannelVerify (RPC::Context& context)
{
    auto const& params (context.params);
    for (auto const& p :
        {jss::public_key, jss::channel_id, jss::amount, jss::signature})
        if (!params.isMember (p))
            return RPC::missing_field_error (p);

    std::string const strPk = params[jss::public_key].asString ();
    auto const pk =
        parseBase58<PublicKey> (TokenType::TOKEN_ACCOUNT_PUBLIC, strPk);
    if (!pk)
        return rpcError (rpcPUBLIC_MALFORMED);

    uint256 channelId;
    if (!channelId.SetHexExact (params[jss::channel_id].asString ()))
        return rpcError (rpcCHANNEL_MALFORMED);

    std::uint64_t drops = 0;
    try
    {
        drops = std::stoul (params[jss::amount].asString ());
    }
    catch (std::exception const&)
    {
        return rpcError (rpcCHANNEL_AMT_MALFORMED);
    }

    std::pair<Blob, bool> sig(strUnHex (params[jss::signature].asString ()));
    if (!sig.second || !sig.first.size ())
        return rpcError (rpcINVALID_PARAMS);

    Serializer msg;
    serializePayChanAuthorization (msg, channelId, XRPAmount (drops));

    Json::Value result;
    result[jss::signature_verified] =
        verify (*pk, msg.slice (), makeSlice (sig.first), /*canonical*/ true);
    return result;
}