Exemplo n.º 1
0
BinaryData BinaryData::getSliceCopy(int32_t start_pos, uint32_t nChar) const
{
   if(start_pos < 0) 
      start_pos = getSize() + start_pos;

   if(start_pos + nChar > getSize())
   {
      cerr << "getSliceCopy: Invalid BinaryData access" << endl;
      return BinaryData();
   }
   return BinaryData(getPtr()+start_pos, nChar);
}
Exemplo n.º 2
0
// Implementing pure virtual method of ColumnBase.
inline void BinaryColumn::insert_rows(size_t row_ndx, size_t num_rows_to_insert,
                                      size_t prior_num_rows, bool insert_nulls)
{
    REALM_ASSERT_DEBUG(prior_num_rows == size());
    REALM_ASSERT(row_ndx <= prior_num_rows);
    REALM_ASSERT(!insert_nulls || m_nullable);

    size_t row_ndx_2 = (row_ndx == prior_num_rows ? realm::npos : row_ndx);
    BinaryData value = m_nullable ? BinaryData() : BinaryData("", 0);
    bool add_zero_term = false;
    do_insert(row_ndx_2, value, add_zero_term, num_rows_to_insert); // Throws
}
Exemplo n.º 3
0
void TxIn::unserialize_checked(uint8_t const * ptr, 
                       uint32_t        size,
                       uint32_t        nbytes, 
                       TxRef           parent, 
                       uint32_t        idx)
{
   parentTx_ = parent;
   index_ = idx;
   uint32_t numBytes = (nbytes==0 ? BtcUtils::TxInCalcLength(ptr, size) : nbytes);
   if (size < numBytes)
      throw BlockDeserializingException();
   dataCopy_.copyFrom(ptr, numBytes);

   if (dataCopy_.getSize()-36 < 1)
      throw BlockDeserializingException();
   scriptOffset_ = 36 + BtcUtils::readVarIntLength(getPtr()+36);

   if (dataCopy_.getSize() < 32)
      throw BlockDeserializingException();
   scriptType_ = BtcUtils::getTxInScriptType(getScriptRef(),
                                             BinaryDataRef(getPtr(),32));

   if(!parentTx_.isInitialized())
   {
      parentHeight_ = UINT32_MAX;
      parentHash_   = BinaryData(0);
   }
}
Exemplo n.º 4
0
inline BinaryData BinaryColumn::get(size_t ndx) const noexcept
{
    REALM_ASSERT_DEBUG(ndx < size());
    if (root_is_leaf()) {
        bool is_big = m_array->get_context_flag();
        BinaryData ret;
        if (!is_big) {
            // Small blobs root leaf
            ArrayBinary* leaf = static_cast<ArrayBinary*>(m_array.get());
            ret = leaf->get(ndx);
        }
        else {
            // Big blobs root leaf
            ArrayBigBlobs* leaf = static_cast<ArrayBigBlobs*>(m_array.get());
            ret = leaf->get(ndx);
        }
        if (!m_nullable && ret.is_null())
            return BinaryData("", 0); // return empty string (non-null)
        return ret;
    }

    // Non-leaf root
    std::pair<MemRef, size_t> p = m_array->get_bptree_leaf(ndx);
    const char* leaf_header = p.first.m_addr;
    size_t ndx_in_leaf = p.second;
    Allocator& alloc = m_array->get_alloc();
    bool is_big = Array::get_context_flag_from_header(leaf_header);
    if (!is_big) {
        // Small blobs
        return ArrayBinary::get(leaf_header, ndx_in_leaf, alloc);
    }
    // Big blobs
    return ArrayBigBlobs::get(leaf_header, ndx_in_leaf, alloc);
}
Exemplo n.º 5
0
void TxOut::unserialize_checked( uint8_t const * ptr,
                         uint32_t size,
                         uint32_t nbytes,
                         TxRef parent,
                         uint32_t idx)
{
   parentTx_ = parent;
   index_ = idx;
   uint32_t numBytes = (nbytes==0 ? BtcUtils::TxOutCalcLength(ptr) : nbytes);
   if (size < numBytes)
      throw BlockDeserializingException();
   dataCopy_.copyFrom(ptr, numBytes);

   scriptOffset_ = 8 + BtcUtils::readVarIntLength(getPtr()+8);
   if (dataCopy_.getSize()-scriptOffset_-getScriptSize() > size)
      throw BlockDeserializingException();
   BinaryDataRef scriptRef(dataCopy_.getPtr()+scriptOffset_, getScriptSize());
   scriptType_ = BtcUtils::getTxOutScriptType(scriptRef);
   uniqueScrAddr_ = BtcUtils::getTxOutScrAddr(scriptRef);

   if(!parentTx_.isInitialized())
   {
      parentHeight_ = UINT32_MAX;
      parentHash_   = BinaryData(0);
   }
}
Exemplo n.º 6
0
  void MzMLSpectrumDecoder::handleBinaryDataArray(xercesc::DOMNode* indexListNode, std::vector<BinaryData>& data_)
  {
    // access result through data_.back()
    data_.push_back(BinaryData());

    XMLCh* TAG_CV = xercesc::XMLString::transcode("cvParam");
    XMLCh* TAG_binary = xercesc::XMLString::transcode("binary");
    XMLCh* TAG_userParam = xercesc::XMLString::transcode("userParam");
    XMLCh* TAG_referenceableParamGroupRef = xercesc::XMLString::transcode("referenceableParamGroupRef");

    // Iterate through binaryDataArray elements
    // only allowed subelements:
    //  - referenceableParamGroupRef (0+)
    //  - cvParam (0+)
    //  - userParam (0+)
    //  - binary (1)
    xercesc::DOMNodeList* index_elems = indexListNode->getChildNodes();
    const  XMLSize_t nodeCount_ = index_elems->getLength();
    for (XMLSize_t j = 0; j < nodeCount_; ++j)
    {
      xercesc::DOMNode* currentNode = index_elems->item(j);
      if (currentNode->getNodeType() &&   // true is not NULL
          currentNode->getNodeType() == xercesc::DOMNode::ELEMENT_NODE)   // is element
      {
        xercesc::DOMElement* currentElement = dynamic_cast<xercesc::DOMElement*>(currentNode);
        if (xercesc::XMLString::equals(currentElement->getTagName(), TAG_binary))
        {
          // TODO do not use expensive xercesc transcoding!
          data_.back().base64 = xercesc::XMLString::transcode(currentNode->getTextContent());
        }
        else if (xercesc::XMLString::equals(currentElement->getTagName(), TAG_CV))
        {
          std::string accession = xercesc::XMLString::transcode(currentElement->getAttribute(xercesc::XMLString::transcode("accession")));
          std::string value = xercesc::XMLString::transcode(currentElement->getAttribute(xercesc::XMLString::transcode("value")));
          std::string name = xercesc::XMLString::transcode(currentElement->getAttribute(xercesc::XMLString::transcode("name")));

          //handleCVParam(data_, accession, value, name);

          Internal::MzMLHandlerHelper::handleBinaryDataArrayCVParam(data_, accession, value, name);
        }
        else if (xercesc::XMLString::equals(currentElement->getTagName(), TAG_userParam))
        {
          std::cout << " unhandled userParam" << std::endl;
        }
        else if (xercesc::XMLString::equals(currentElement->getTagName(), TAG_referenceableParamGroupRef))
        {
          std::cout << " unhandled referenceableParamGroupRef" << std::endl;
        }
        else
        {
          //std::cout << "unhandled" << (string)xercesc::XMLString::transcode(currentNode->getNodeName() << std::endl;
        }
      }
    }

    xercesc::XMLString::release(&TAG_CV);
    xercesc::XMLString::release(&TAG_binary);
    xercesc::XMLString::release(&TAG_userParam);
    xercesc::XMLString::release(&TAG_referenceableParamGroupRef);
  }
Exemplo n.º 7
0
UnspentTxOut::UnspentTxOut(void) :
   txHash_(BtcUtils::EmptyHash()),
   txOutIndex_(0),
   txHeight_(0),
   value_(0),
   script_(BinaryData(0)),
   isMultisigRef_(false)
{
   // Nothing to do here
}
Exemplo n.º 8
0
BinaryData BinaryData::GetDataRef(size_t offset, size_t inSize)
{
    if (inSize > Size())
        inSize = Size();
    if (offset > Size())
        offset = Size();
    if (offset + inSize > Size())
        inSize = Size() - offset;
    return BinaryData(*this + offset, inSize, false);
}
Exemplo n.º 9
0
void WalletGroup::updateLedgerFilter(const vector<BinaryData>& walletsList)
{
   ReadWriteLock::ReadLock rl(lock_);
   for (auto& wlt : values(wallets_))
      wlt->uiFilter_ = false;

   for (auto walletID : walletsList)
      wallets_[walletID]->uiFilter_ = true;

   bdvPtr_->flagRefresh(BDV_filterChanged, BinaryData());
}
Exemplo n.º 10
0
void tbl_nativeDoByteArray(M doBinary, T* pTable, JNIEnv* env, jlong columnIndex, jlong rowIndex, jbyteArray dataArray)
{
    jbyte* bytePtr = env->GetByteArrayElements(dataArray, NULL);
    if (!bytePtr) {
        ThrowException(env, IllegalArgument, "doByteArray");
        return;
    }
    size_t dataLen = S(env->GetArrayLength(dataArray));
    (pTable->*doBinary)( S(columnIndex), S(rowIndex), BinaryData(reinterpret_cast<char*>(bytePtr), dataLen));
    env->ReleaseByteArrayElements(dataArray, bytePtr, 0);
}
Exemplo n.º 11
0
HashString TxIOPair::getTxHashOfInput(const LMDBBlockDatabase *db) const
{
   if (!hasTxIn())
      return BtcUtils::EmptyHash();
   else if (txHashOfInput_.getSize() == 32)
      return txHashOfInput_;
   else if (txRefOfInput_.isInitialized() && db != nullptr)
   {
      txHashOfInput_ = txRefOfInput_.attached(db).getThisHash();
      return txHashOfInput_;
   }

   return BinaryData(0);
}
Exemplo n.º 12
0
BinaryData BtcUtils::getGroestlHash(uint8_t const * strToHash, uint32_t nBytes) {
    sph_groestl512_context  ctx_gr[2];
    static unsigned char pblank[1];
    uint8_t hash1[64];
	
    sph_groestl512_init(&ctx_gr[0]);
    sph_groestl512 (&ctx_gr[0], strToHash ? strToHash : pblank, nBytes);
    sph_groestl512_close(&ctx_gr[0], hash1);
	
	uint8_t hash2[64];
	sph_groestl512_init(&ctx_gr[1]);
	sph_groestl512(&ctx_gr[1], hash1, 64);
	sph_groestl512_close(&ctx_gr[1], hash2);

	return BinaryData(hash2, 32);
}
Exemplo n.º 13
0
void BlockHeader::unserialize(uint8_t const * ptr, uint32_t size)
{
   if (size < HEADER_SIZE)
      throw BlockDeserializingException();
   dataCopy_.copyFrom(ptr, HEADER_SIZE);
   BtcUtils::getHash256(dataCopy_.getPtr(), HEADER_SIZE, thisHash_);
   difficultyDbl_ = BtcUtils::convertDiffBitsToDouble( 
                              BinaryDataRef(dataCopy_.getPtr()+72, 4));
   isInitialized_ = true;
   nextHash_ = BinaryData(0);
   blockHeight_ = UINT32_MAX;
   difficultySum_ = -1;
   isMainBranch_ = false;
   isOrphan_ = true;
   numTx_ = UINT32_MAX;
}
Exemplo n.º 14
0
void BlockHeaderRef::unserialize(uint8_t const * ptr)
{
   self_.setRef(ptr, HEADER_SIZE);
   BtcUtils::getHash256(self_.getPtr(), HEADER_SIZE, thisHash_);
   difficultyDbl_ = BtcUtils::convertDiffBitsToDouble( 
                              BinaryDataRef(self_.getPtr()+72, 4));
   isInitialized_ = true;
   nextHash_ = BinaryData(0);
   blockHeight_ = UINT32_MAX;
   blockNumBytes_ = 0;
   blkByteLoc_ = 0;
   difficultySum_ = -1;
   isMainBranch_ = false;
   isOrphan_ = true;
   isFinishedCalc_ = false;
   isOnDiskYet_ = false;
   txPtrList_ = vector<TxRef*>(0);
}
Exemplo n.º 15
0
void BlockDataViewer::flagRefresh(BDV_refresh refresh, const BinaryData& refreshID)
{ 
   if (saf_->bdmIsRunning() == false)
      return;

   unique_lock<mutex> lock(refreshLock_);

   if (refresh_ != BDV_refreshAndRescan)
   {
      if (refresh == BDV_refreshAndRescan)
         refresh_ = BDV_refreshAndRescan;
      else
         refresh_ = BDV_refreshSkipRescan;
   }

   if (refreshID.getSize())
      refreshIDSet_.insert(refreshID);
   
   if (refresh == BDV_filterChanged)
      refreshIDSet_.insert(BinaryData("wallet_filter_changed"));

   notifyMainThread();
}
Exemplo n.º 16
0
inline BinaryData TrivialReplication::get_uncommitted_changes() const noexcept
{
    const char* data = m_transact_log_buffer.data();
    size_t size = write_position() - data;
    return BinaryData(data, size);
}
Exemplo n.º 17
0
AbstractShader::BinaryData DXShader::GetBinary() const
{
  return BinaryData(m_bytecode->Data(), m_bytecode->Data() + m_bytecode->Size());
}
Exemplo n.º 18
0
void tbl_nativeDoMixed(M doMixed, T* pTable, JNIEnv* env, jlong columnIndex, jlong rowIndex, jobject jMixedValue)
{
    DataType valueType = GetMixedObjectType(env, jMixedValue);
    switch(valueType) {
    case type_Int:
        {
            jlong longValue = GetMixedIntValue(env, jMixedValue);
            (pTable->*doMixed)( S(columnIndex), S(rowIndex), Mixed(static_cast<int64_t>(longValue)));
            return;
        }
    case type_Float:
        {
            jfloat floatValue = GetMixedFloatValue(env, jMixedValue);
            (pTable->*doMixed)( S(columnIndex), S(rowIndex), Mixed(floatValue));
            return;
        }
    case type_Double:
        {
            jdouble doubleValue = GetMixedDoubleValue(env, jMixedValue);
            (pTable->*doMixed)( S(columnIndex), S(rowIndex), Mixed(doubleValue));
            return;
        }
    case type_Bool:
        {
            jboolean boolValue = GetMixedBooleanValue(env, jMixedValue);
            (pTable->*doMixed)( S(columnIndex), S(rowIndex), Mixed(boolValue != 0 ? true : false));
            return;
        }
    case type_String:
        {
            jstring stringValue = GetMixedStringValue(env, jMixedValue);
            JStringAccessor string(env, stringValue); // throws
            (pTable->*doMixed)( S(columnIndex), S(rowIndex), StringData(string));
            return;
        }
    case type_DateTime:
        {
            jlong dateTimeValue = GetMixedDateTimeValue(env, jMixedValue);
            DateTime date(dateTimeValue);
            (pTable->*doMixed)( S(columnIndex), S(rowIndex), Mixed(date));
            return;
        }
    case type_Binary:
        {
            jint mixedBinaryType = GetMixedBinaryType(env, jMixedValue);
            if (mixedBinaryType == 0) {
                jbyteArray dataArray = GetMixedByteArrayValue(env, jMixedValue);
                if (!dataArray)
                    break;
                char* data = reinterpret_cast<char*>(env->GetByteArrayElements(dataArray, NULL));
                if (!data)
                    break;
                size_t size = S(env->GetArrayLength(dataArray));
                (pTable->*doMixed)( S(columnIndex), S(rowIndex), BinaryData(data, size));
                env->ReleaseByteArrayElements(dataArray, reinterpret_cast<jbyte*>(data), 0);
                return;
            }
            else if (mixedBinaryType == 1) {
                jobject jByteBuffer = GetMixedByteBufferValue(env, jMixedValue);
                if (!jByteBuffer)
                    break;
                BinaryData binaryData;
                if (GetBinaryData(env, jByteBuffer, binaryData))
                    (pTable->*doMixed)( S(columnIndex), S(rowIndex), binaryData);
                return;
            }
            break; // failed
        }
    case type_Table:
        {
            (pTable->*doMixed)( S(columnIndex), S(rowIndex), Mixed::subtable_tag());
            return;
        }
    case type_Mixed:
        break;
    case type_Link:
        break;
    case type_LinkList:
        break;
    }
    TR_ERR("ERROR: nativeSetMixed() failed.")
    ThrowException(env, IllegalArgument, "nativeSetMixed()");
}
Exemplo n.º 19
0
void BlockchainScanner::scanBlockData(shared_ptr<BlockDataBatch> batch)
{
   //getBlock lambda
   auto getBlock = [&](unsigned height)->BlockData
   {
      auto iter = batch->blocks_.find(height);
      if (iter == batch->blocks_.end())
      {
         //TODO: encapsulate in try block to catch deser errors and signal pull thread
         //termination before exiting scope. cant have the scan thread hanging if this
         //one fails. Also update batch->end_ if we didn't go as far as that block height

         //grab block file map
         BlockHeader* blockheader = nullptr;
         blockheader = &blockchain_->getHeaderByHeight(height);

         auto filenum = blockheader->getBlockFileNum();
         auto mapIter = batch->fileMaps_.find(filenum);
         if (mapIter == batch->fileMaps_.end())
         {
            //we haven't grabbed that file map yet
            auto insertPair = batch->fileMaps_.insert(
               make_pair(filenum, move(blockDataLoader_.get(filenum, true))));

            mapIter = insertPair.first;
         }

         auto filemap = mapIter->second.get();

         //find block and deserialize it
         try
         {
            BlockData bdata;
            bdata.deserialize(
               filemap->getPtr() + blockheader->getOffset(),
               blockheader->getBlockSize(),
               blockheader, false);

            auto insertPair = batch->blocks_.insert(make_pair(height, move(bdata)));
            iter = insertPair.first;
         }
         catch (...)
         {
            LOGERR << "unknown block deser error during scan at height #" << height;
            batch->exceptionPtr_ = current_exception();
            return BlockData();
         }
      }

      return iter->second;
   };

   //parser lambda
   auto blockDataLoop = [&](function<void(const BlockData&)> callback)
   {
      auto currentBlock = batch->start_;

      while (currentBlock <= batch->end_)
      {
         BlockData&& bdata = getBlock(currentBlock);
         if (!bdata.isInitialized())
            return;

         callback(bdata);

         currentBlock += totalThreadCount_;
      }
   };

   //txout lambda
   auto txoutParser = [&](const BlockData& blockdata)->void
   {
      //TODO: flag isMultisig

      const BlockHeader* header = blockdata.header();

      //update processed height
      auto topHeight = header->getBlockHeight();
      batch->highestProcessedHeight_ = topHeight;

      auto& txns = blockdata.getTxns();
      for (unsigned i = 0; i < txns.size(); i++)
      {
         const BCTX& txn = *(txns[i].get());
         for (unsigned y = 0; y < txn.txouts_.size(); y++)
         {
            auto& txout = txn.txouts_[y];

            BinaryRefReader brr(
               txn.data_ + txout.first, txout.second);
            brr.advance(8);
            unsigned scriptSize = (unsigned)brr.get_var_int();
            auto&& scrAddr = BtcUtils::getTxOutScrAddr(
               brr.get_BinaryDataRef(scriptSize));

            if (!scrAddrFilter_->hasScrAddress(scrAddr))
               continue;

            //if we got this far, this txout is ours
            //get tx hash
            auto& txHash = txn.getHash();

            //construct StoredTxOut
            StoredTxOut stxo;
            stxo.dataCopy_ = BinaryData(
               txn.data_ + txout.first, txout.second);
            stxo.parentHash_ = txHash;
            stxo.blockHeight_ = header->getBlockHeight();
            stxo.duplicateID_ = header->getDuplicateID();
            stxo.txIndex_ = i;
            stxo.txOutIndex_ = y;
            stxo.scrAddr_ = scrAddr;
            stxo.spentness_ = TXOUT_UNSPENT;
            stxo.parentTxOutCount_ = txn.txouts_.size();
            stxo.isCoinbase_ = txn.isCoinbase_;
            auto value = stxo.getValue();

            auto&& hgtx = DBUtils::heightAndDupToHgtx(
               stxo.blockHeight_, stxo.duplicateID_);
            
            auto&& txioKey = DBUtils::getBlkDataKeyNoPrefix(
               stxo.blockHeight_, stxo.duplicateID_,
               i, y);

            //update utxos_
            auto& stxoHashMap = batch->utxos_[txHash];
            stxoHashMap.insert(make_pair(y, move(stxo)));

            //update ssh_
            auto& ssh = batch->ssh_[scrAddr];
            auto& subssh = ssh.subHistMap_[hgtx];
            
            //deal with txio count in subssh at serialization
            TxIOPair txio;
            txio.setValue(value);
            txio.setTxOut(txioKey);
            txio.setFromCoinbase(txn.isCoinbase_);
            subssh.txioMap_.insert(make_pair(txioKey, move(txio)));
         }
      }
   };

   //txin lambda
   auto txinParser = [&](const BlockData& blockdata)->void
   {
      const BlockHeader* header = blockdata.header();
      auto& txns = blockdata.getTxns();

      for (unsigned i = 0; i < txns.size(); i++)
      {
         const BCTX& txn = *(txns[i].get());

         for (unsigned y = 0; y < txn.txins_.size(); y++)
         {
            auto& txin = txn.txins_[y];
            BinaryDataRef outHash(
               txn.data_ + txin.first, 32);

            auto utxoIter = utxoMap_.find(outHash);
            if (utxoIter == utxoMap_.end())
               continue;

            unsigned txOutId = READ_UINT32_LE(
               txn.data_ + txin.first + 32);

            auto idIter = utxoIter->second.find(txOutId);
            if (idIter == utxoIter->second.end())
               continue;

            //if we got this far, this txins consumes one of our utxos

            //create spent txout
            auto&& hgtx = DBUtils::getBlkDataKeyNoPrefix(
               header->getBlockHeight(), header->getDuplicateID());

            auto&& txinkey = DBUtils::getBlkDataKeyNoPrefix(
               header->getBlockHeight(), header->getDuplicateID(),
               i, y);

            StoredTxOut stxo = idIter->second;
            stxo.spentness_ = TXOUT_SPENT;
            stxo.spentByTxInKey_ = txinkey;

            //if this tx's hash was never pulled, let's add it to the stxo's
            //parent hash, in order to keep track of this tx in the hint db
            if (txn.txHash_.getSize() == 0)
               stxo.parentHash_ = move(txn.getHash());

            //add to ssh_
            auto& ssh = batch->ssh_[stxo.getScrAddress()];
            auto& subssh = ssh.subHistMap_[hgtx];

            //deal with txio count in subssh at serialization
            TxIOPair txio;
            auto&& txoutkey = stxo.getDBKey(false);
            txio.setTxOut(txoutkey);
            txio.setTxIn(txinkey);
            txio.setValue(stxo.getValue());
            subssh.txioMap_[txoutkey] = move(txio);
            
            //add to spentTxOuts_
            batch->spentTxOuts_.push_back(move(stxo));
         }
      }
   };

   //txout loop
   blockDataLoop(txoutParser);

   //done with txouts, fill the future flag and wait on the mutex 
   //to move to txins processing
   batch->flagUtxoScanDone();
   unique_lock<mutex> txinLock(batch->parseTxinMutex_);

   //txins loop
   blockDataLoop(txinParser);
}
Exemplo n.º 20
0
void StackResolver::processOpCode(const OpCode& oc)
{
   if (oc.opcode_ >= 1 && oc.opcode_ <= 75)
   {
      pushdata(oc.dataRef_);
      return;
   }

   if (oc.opcode_ >= 81 && oc.opcode_ <= 96)
   {
      unsigned val = oc.opcode_ - 80;
      push_int(val);
      return;
   }

   opCodeCount_++;
   switch (oc.opcode_)
   {
   case OP_0:
      pushdata(BinaryData());
      break;

   case OP_PUSHDATA1:
   case OP_PUSHDATA2:
   case OP_PUSHDATA4:
      pushdata(oc.dataRef_);
      break;

   case OP_DUP:
      op_dup();
      break;

   case OP_HASH160:
   case OP_SHA256:
   {
      opHash_ = true;
      op_1item_verify(oc);
      break;
   }

   case OP_RIPEMD160:
   case OP_HASH256:
      op_1item_verify(oc);
      break;

   case OP_EQUAL:
   {
      if (opCodeCount_ == 2 && opHash_)
         isP2SH_ = true;
      op_2items(oc);
      break;
   }

   case OP_CHECKSIG:
      op_2items(oc);
      break;

   case OP_EQUALVERIFY:
   case OP_CHECKSIGVERIFY:
      op_2items_verify(oc);
      break;

   case OP_CHECKMULTISIG:
   case OP_CHECKMULTISIGVERIFY:
      push_op_code(oc);
      break;

   default:
      throw ScriptException("opcode not implemented with reverse stack");
   }
}
bool ScrAddrFilter::registerAddressBatch(
   const map<shared_ptr<BtcWallet>, vector<BinaryData>>& wltNAddrMap, 
   bool areNew)
{
   /***
   Gets a scrAddr ready for loading. Returns false if the BDM is initialized,
   in which case wltPtr will be called back with the address once it is ready

   doScan: 
      1: don't scan, new addresses
      0: scan while taking count of the existing history
     -1: wipe existing history then scan
   ***/

   //check if the BDM is initialized. There ought to be a better way than
   //checking the top block
   if (bdmIsRunning())
   {
      //BDM is initialized and maintenance thread is running, check mode
      if (armoryDbType_ == ARMORY_DB_SUPER)
      {
         //supernode: nothing to do, signal the wallet that its scrAddr bulk 
         //is ready by passing isNew as true. Pass a blank BinaryData for the 
         //top scanned block hash in this case, it will be ignored anyways      
         
         while (mergeLock_.fetch_or(1, memory_order_acquire));
         for (auto& batch : wltNAddrMap)
         {
            for (auto& sa : batch.second)
               scrAddrDataForSideScan_.scrAddrsToMerge_.insert({ sa, 0 });
            mergeFlag_ = true;
         }
         mergeLock_.store(0, memory_order_release);

         for (auto& batch : wltNAddrMap)
         {
            batch.first->prepareScrAddrForMerge(
               batch.second, true, BinaryData());

            batch.first->needsRefresh();
         }

         return false;
      }

      //check DB for the scrAddr's SSH
      StoredScriptHistory ssh;
         
      ScrAddrFilter* topChild = this;
      while (topChild->child_)
         topChild = topChild->child_.get();

      topChild->child_ = shared_ptr<ScrAddrFilter>(copy());
      ScrAddrFilter* sca = topChild->child_.get();

      sca->setRoot(this);
        
      if (!areNew)
      {
         //mark existing history for wipe and rescan from block 0
         sca->doScan_ = true;

         for (auto& batch : wltNAddrMap)
         {
            for (const auto& scrAddr : batch.second)
               sca->regScrAddrForScan(scrAddr, 0);
         }
      }
      else
      {
         //mark addresses as fresh to skip DB scan
         sca->doScan_ = false;
         for (auto& batch : wltNAddrMap)
         {
            for (const auto& scrAddr : batch.second)
               sca->regScrAddrForScan(scrAddr, 0);
         }
      }

      sca->buildSideScanData(wltNAddrMap);
      flagForScanThread();

      return false;
   }
   else
   {
      //BDM isnt initialized yet, the maintenance thread isnt running, 
      //just register the scrAddr and return true.
      for (auto& batch : wltNAddrMap)
      {
         for (const auto& scrAddr : batch.second)
            scrAddrMap_.insert(make_pair(scrAddr, 0));
      }

      return true;
   }
}
Exemplo n.º 22
0
BinaryData SigHashDataLegacy::getDataForSigHashAll(const TransactionStub& stub, 
   BinaryDataRef subScript, unsigned inputIndex)
{
   //grab subscript
   auto lastCSoffset = stub.getLastCodeSeparatorOffset(inputIndex);
   auto subScriptLen = subScript.getSize() - lastCSoffset;
   auto&& presubscript = subScript.getSliceRef(lastCSoffset, subScriptLen);

   //tokenize op_cs chunks
   auto&& tokens = tokenize(presubscript, OP_CODESEPARATOR);

   BinaryData subscript;
   if (tokens.size() == 1)
   {
      subscript = move(presubscript);
   }
   else
   {
      for (auto& token : tokens)
      {
         subscript.append(token);
      }
   }

   //isolate outputs
   auto&& serializedOutputs = stub.getSerializedOutputScripts();

   //isolate inputs
   auto&& txinsData = stub.getTxInsData();
   auto txin_count = txinsData.size();
   BinaryWriter strippedTxins;

   for (unsigned i=0; i < txin_count; i++)
   {
      strippedTxins.put_BinaryData(txinsData[i].outputHash_);
      strippedTxins.put_uint32_t(txinsData[i].outputIndex_);

      if (inputIndex != i)
      {
         //put empty varint
         strippedTxins.put_var_int(0);

         //and sequence
         strippedTxins.put_uint32_t(txinsData[i].sequence_);
      }
      else
      {
         //scriptsig
         strippedTxins.put_var_int(subscript.getSize());
         strippedTxins.put_BinaryData(subscript);
         
         //sequence
         strippedTxins.put_uint32_t(txinsData[i].sequence_);
      }
   }

   //wrap it up
   BinaryWriter scriptSigData;

   //version
   scriptSigData.put_uint32_t(stub.getVersion());

   //txin count
   scriptSigData.put_var_int(txin_count);

   //txins
   scriptSigData.put_BinaryData(strippedTxins.getData());

   //txout count
   scriptSigData.put_var_int(stub.getTxOutCount());

   //txouts
   scriptSigData.put_BinaryData(serializedOutputs);

   //locktime
   scriptSigData.put_uint32_t(stub.getLockTime());

   //sighashall
   scriptSigData.put_uint32_t(1);

   return BinaryData(scriptSigData.getData());
}
Exemplo n.º 23
0
BinaryData TxOut::getScript(void) 
{ 
   return BinaryData( dataCopy_.getPtr()+scriptOffset_, getScriptSize() );
}
Exemplo n.º 24
0
BinaryData TxOutRef::getScript(void) 
{ 
   return BinaryData( self_.getPtr()+scriptOffset_, getScriptSize() );
}
Exemplo n.º 25
0
BinaryData TxIn::getScript(void) const
{ 
   uint32_t scrLen = (uint32_t)BtcUtils::readVarInt(getPtr()+36);
   return BinaryData(getPtr() + getScriptOffset(), scrLen);
}