Example #1
0
/** Determine whether a signature is canonical.
    Canonical signatures are important to protect against signature morphing
    attacks.
    @param vSig the signature data
    @param sigLen the length of the signature
    @param strict_param whether to enforce strictly canonical semantics

    @note For more details please see:
    https://ripple.com/wiki/Transaction_Malleability
    https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
    https://github.com/sipa/bitcoin/commit/58bc86e37fda1aec270bccb3df6c20fbd2a6591c
*/
boost::optional<ECDSACanonicality>
ecdsaCanonicality (Slice const& sig)
{
    static uint264 const G(
        "0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");

    // The format of a signature should be:
    // <30> <len> [ <02> <lenR> <R> ] [ <02> <lenS> <S> ]
    if ((sig.size() < 8) || (sig.size() > 72))
        return boost::none;
    if ((sig[0] != 0x30) || (sig[1] != (sig.size() - 2)))
        return boost::none;
    Slice p = sig + 2;
    auto r = sigPart(p);
    auto s = sigPart(p);
    if (! r || ! s || ! p.empty())
        return boost::none;

    uint264 R(sliceToHex(*r));
    uint264 S(sliceToHex(*s));

    if (R >= G)
        return boost::none;
    if (S >= G)
        return boost::none;
    // (R,S) and (R,G-S) are canonical,
    // but is fully canonical when S <= G-S
    auto const Sp = G - S;
    if (S > Sp)
        return ECDSACanonicality::canonical;
    return ECDSACanonicality::fullyCanonical;
}
Example #2
0
bool Layout::load_2nd_superblock()
{
    Slice buffer = alloc_aligned_buffer(SUPER_BLOCK_SIZE);
    if (!buffer.size()) {
        LOG_ERROR("alloc_aligned_buffer error, size " << SUPER_BLOCK_SIZE);
        return false;
    }

    if (!read_data(SUPER_BLOCK_SIZE, buffer)) {
        LOG_ERROR("try to read 2nd superblock error");
        return false;
    }

    LOG_TRACE("read 2nd superblock ok");
    Block block(buffer, 0, SUPER_BLOCK_SIZE);
    BlockReader reader(&block);
    if (!read_superblock(reader)) {
        LOG_ERROR("2nd superblock is invalid");
        free_buffer(buffer);
        return false;
    }

    LOG_TRACE("load 2nd superblock ok");
    free_buffer(buffer);
    return true;
}
Example #3
0
bool Layout::flush_superblock()
{
    Slice buffer = alloc_aligned_buffer(SUPER_BLOCK_SIZE);
    if (!buffer.size()) {
        LOG_ERROR("alloc_aligned_buffer fail, size " << SUPER_BLOCK_SIZE);
        return false;
    }

    Block block(buffer, 0, 0);
    BlockWriter writer(&block);
    if (!write_superblock(writer)) {
        assert(false);
    }

    // double write to ensure superblock is correct

    if (!write_data(0, buffer)) {
        LOG_ERROR("flush 1st superblock error");
        free_buffer(buffer);
        return false;
    }

    LOG_TRACE("flush 1st superblock ok");

    if (!write_data(SUPER_BLOCK_SIZE, buffer)) {
        LOG_ERROR("flush 2nd superblock error");
        free_buffer(buffer);
        return false;
    }

    LOG_TRACE("flush 2nd superblock ok");
    free_buffer(buffer);
    return true;
}
Example #4
0
void PlayLayer::createAndDropSlice(int row, int col)
{
    idSlice++;
    
	Size size = Director::getInstance()->getWinSize();
    Point endPosition = positionOfSlice(row, col);
	Point startPosition = Point(endPosition.x, endPosition.y + size.height / 2);
    float speed = startPosition.y / (size.height);
    
    int i = rand()%(6);
    Slice* slice = Slice::create(Point(row, col), i);
   
	slice->setPosition(startPosition);
    slice->setID(idSlice - 1);
    slice->setINDEX(Vec2(row, col));

	slice->runAction(MoveTo::create(speed, endPosition));// roi xuong

	
    
    this->addChild(slice);
    
    listSlice->pushBack(slice);
    
	
}
Example #5
0
void Layout::async_read(bid_t bid, Block **block, Callback *cb)
{
    BlockMeta meta;
    if (!get_block_meta(bid, meta)) {
        LOG_INFO("Read Block failed, cannot find block bid " << hex << bid << dec);
        cb->exec(false);
        return;
    }

    Slice buffer = alloc_aligned_buffer(meta.total_size);
    if (!buffer.size()) {
        LOG_ERROR("alloc_aligned_buffer fail, size " << meta.total_size);
        cb->exec(false);
        return;
    }

    AsyncReadReq *req = new AsyncReadReq();
    req->bid = bid;
    req->cb = cb;
    req->block = block;
    req->buffer = buffer;
    req->meta = meta;

    Callback *ncb = new Callback(this, &Layout::handle_async_read, req);

    ScopedMutex lock(&mtx_);
    fly_reads_ ++;
    lock.unlock();

    aio_file_->async_read(meta.offset, buffer, ncb, aio_complete_handler);
}
Example #6
0
void Base64::encode(const Slice& bytes, std::string* output) {
  output->assign(ToBase64Iter(bytes.begin()), ToBase64Iter(bytes.end()));

  // Boost does not handle Base64 padding.
  const auto num_padding_chars = (3 - (bytes.size() % 3)) % 3;
  output->append(num_padding_chars, '=');
}
Example #7
0
        int hot_optimize(const Slice &left, const Slice &right, OptimizeCallback callback, uint64_t *loops_run = NULL) const {
            DBT ldbt = left.dbt();
            DBT rdbt = right.dbt();

            class WrappedOptimizeCallback {
                OptimizeCallback &_oc;
                size_t _loops;

            public:
                WrappedOptimizeCallback(OptimizeCallback &oc)
                    : _oc(oc),
                      _loops(0)
                {}

                static int call(void *extra, float progress) {
                    WrappedOptimizeCallback *e = static_cast<WrappedOptimizeCallback *>(extra);
                    return e->_oc(progress, ++e->_loops);
                }
            } woc(callback);

            uint64_t dummy;
            return _db->hot_optimize(_db, &ldbt, &rdbt,
                                     &WrappedOptimizeCallback::call, &woc,
                                     loops_run == NULL ? &dummy : loops_run);
        }
Example #8
0
 bool Ardb::WakeBlockList(Context& ctx, const Slice& key, const std::string& value)
 {
     DBItemKey kk;
     kk.db = ctx.currentDB;
     kk.key.assign(key.data(), key.size());
     WriteLockGuard<SpinRWLock> guard(m_block_ctx_lock);
     BlockContextTable::iterator fit = m_block_context_table.find(kk);
     if (fit != m_block_context_table.end())
     {
         while (!fit->second.empty())
         {
             Context* cctx = fit->second.front();
             if (NULL
                     != cctx&& cctx->block != NULL && NULL != cctx->client && cctx->block->block_state == BLOCK_STATE_BLOCKED)
             {
                 cctx->block->waked_key = kk;
                 cctx->block->waked_value = value;
                 cctx->block->block_state = BLOCK_STATE_WAKING;
                 cctx->client->GetService().AsyncIO(cctx->client->GetID(), WakeBlockedConnCallback, cctx);
                 fit->second.pop_front();
                 return true;
             }
             fit->second.pop_front();
         }
     }
     return false;
 }
Example #9
0
static bool visitArray(
    Slice const& value,
    std::function<bool(Slice const& key, Slice const& value)> const& func) {
  ArrayIterator it(value);

  while (it.valid()) {
    // sub-object?
    Slice v = it.value();
    bool const isCompound = (v.isObject() || v.isArray());

    if (isCompound && order == Collection::PreOrder) {
      if (!doVisit<order>(v, func)) {
        return false;
      }
    }

    if (!func(Slice(), v)) {
      return false;
    }

    if (isCompound && order == Collection::PostOrder) {
      if (!doVisit<order>(v, func)) {
        return false;
      }
    }

    it.next();
  }

  return true;
}
Example #10
0
bool Node::handle<SET>(VPackSlice const& slice) {
  Slice val = slice.get("new");

  if (val.isObject()) {
    if (val.hasKey("op")) {  // No longer a keyword but a regular key "op"
      if (_children.find("op") == _children.end()) {
        _children["op"] = std::make_shared<Node>("op", this);
      }
      *(_children["op"]) = val.get("op");
    } else {  // Deeper down
      this->applies(val);
    }
  } else {
    *this = val;
  }

  if (slice.hasKey("ttl")) {
    VPackSlice ttl_v = slice.get("ttl");
    if (ttl_v.isNumber()) {
      long ttl = 1000l * ((ttl_v.isDouble())
                              ? static_cast<long>(slice.get("ttl").getDouble())
                              : static_cast<long>(slice.get("ttl").getInt()));
      addTimeToLive(ttl);
    } else {
      LOG_TOPIC(WARN, Logger::AGENCY)
          << "Non-number value assigned to ttl: " << ttl_v.toJson();
    }
  }

  return true;
}
Example #11
0
Seed::Seed (Slice const& slice)
{
    if (slice.size() != buf_.size())
        LogicError("Seed::Seed: invalid size");
    std::memcpy(buf_.data(),
        slice.data(), buf_.size());
}
Example #12
0
PublicKey::PublicKey (Slice const& slice)
{
    if(! publicKeyType(slice))
        LogicError("PublicKey::PublicKey invalid type");
    size_ = slice.size();
    std::memcpy(buf_, slice.data(), slice.size());
}
Example #13
0
					void Put(const Slice& key, const Slice& value)
					{
						std::string str(key.data(), key.size());
						std::string v(value.data(), value.size());
						dels.erase(str);
						inserts[str] = v;
					}
Example #14
0
Result<size_t> SslFd::write(Slice slice) {
  openssl_clear_errors("Before SslFd::write");
  auto size = SSL_write(ssl_handle_, slice.data(), static_cast<int>(slice.size()));
  if (size <= 0) {
    return process_ssl_error(size, &write_mask_);
  }
  return size;
}
Example #15
0
double RestraintCache::get_score(kernel::Restraint *r, const Subset &s,
                                 const Assignment &a) const {
  IMP_OBJECT_LOG;
  set_was_used(true);
  Slice slice = get_slice(r, s);
  Assignment ra = slice.get_sliced(a);
  return get_score(r, ra);
}
Example #16
0
	bool write_string(Slice<char>& buffer, StringView v)
	{
		if (buffer.size() < v.length()) return false;
		
		memcpy(buffer.ptr(), v.c_str(), v.length());
		buffer.trim_front(v.length());
		return true;
	}
Example #17
0
 void LevelDBEngine::CompactRange(const Slice& begin, const Slice& end)
 {
     leveldb::Slice s(begin.data(), begin.size());
     leveldb::Slice e(end.data(), end.size());
     leveldb::Slice* start = s.size() > 0 ? &s : NULL;
     leveldb::Slice* endpos = e.size() > 0 ? &e : NULL;
     m_db->CompactRange(start, endpos);
 }
Example #18
0
 Status Put(const Slice &key, const Slice &value) noexcept override
 {
     assert( Valid() );
     char buf[prefix.size() + key.size()];
     (void) memcpy(buf, prefix.data(), prefix.size());
     (void) memcpy(buf + prefix.size(), key.data(), key.size());
     return sandwich->base.Put(Slice(buf, sizeof(buf)), value);
 }
Example #19
0
	void OperateRecord::Insert(const Slice& dbKey,const Slice& dbValue)
	{
		std::string strKey = dbKey.ToString() , strValue = dbValue.ToString() ;
		m_objStream << OPERATE_RECODE_INSERT;
		m_objStream << strKey << strValue;

		++m_nCount;
	}
Example #20
0
 Status Delete(const Slice &key) noexcept override
 {
     assert( Valid() );
     char buf[prefix.size() + key.size()];
     (void) memcpy(buf, prefix.data(), prefix.size());
     (void) memcpy(buf + prefix.size(), key.data(), key.size());
     return sandwich->base.Delete(Slice(buf, sizeof(buf)));
 }
Example #21
0
std::shared_ptr<Texture> createSpotTexture(Slice &slice)
{
	Vector3d color1 = slice.findVector();
	Vector3d color2 = slice.findVector();
	double radius = slice.findDouble();
	assert(slice.eof());
	return std::shared_ptr<Texture>(new SpotTexture(color1, color2, radius));
}
Example #22
0
 void LMDBIterator::Seek(const Slice& target)
 {
     m_key.mv_data = const_cast<char*>(target.data());
     m_key.mv_size = target.size();
     int rc = mdb_cursor_get(m_cursor, &m_key, &m_value, MDB_SET_RANGE);
     CHECK_OP(rc);
     m_valid = rc == 0;
 }
Example #23
0
	virtual int Compare(const Slice& a, const Slice& b) const
	{
		uint64_t* idA = (uint64_t*)a.data();
		uint64_t* idB = (uint64_t*)b.data();
		int64_t delta = (*idA - *idB);
		if (delta == 0) return 0;
		return delta < 0 ? -1 : 1;
	}
Example #24
0
/*!
 ************************************************************************
 * \brief
 *    The routine performs transform,quantization,inverse transform, adds the diff.
 *    to the prediction and writes the result to the decoded luma frame. Includes the
 *    RD constrained quantization also. Used for CAVLC.
 *
 * \par Input:
 *    b8: Block position inside a macro block (0,1,2,3).
 *
 * \par Output:
 *    nonzero: 0 if no levels are nonzero.  1 if there are nonzero levels.
 *    coeff_cost: Counter for nonzero coefficients, used to discard expensive levels.
 ************************************************************************
 */
int residual_transform_quant_luma_8x8_cavlc(Macroblock *currMB, ColorPlane pl, int b8, int *coeff_cost, int intra)
{
  VideoParameters *p_Vid = currMB->p_Vid;
  int nonzero = FALSE; 

  int block_x = 8*(b8 & 0x01);
  int block_y = 8*(b8 >> 1);
  int pl_off = b8+ (pl<<2);
  imgpel **img_enc = p_Vid->enc_picture->p_curr_img;
  Slice *currSlice = currMB->p_Slice;
  imgpel **mb_pred = currSlice->mb_pred[pl];  
  int    **mb_ores = currSlice->mb_ores[pl];   
  int    **mb_rres = currSlice->mb_rres[pl];   

  int max_imgpel_value   = p_Vid->max_imgpel_value;
  
  int qp = currMB->qp_scaled[pl];

  //if (check_zero(&mb_ores[block_y], block_x) != 0)
  {
    // Variable p_Quant and some of its parameters could be all set outside 
    // to speed up the code (e.g. field mode, coeff_cost, etc). 
    QuantParameters *p_Quant = p_Vid->p_Quant;

    QuantMethods quant_methods;
    quant_methods.block_x    = block_x;
    quant_methods.block_y    = block_y;
    quant_methods.qp         = qp;
    quant_methods.q_params   = p_Quant->q_params_8x8[pl][intra][qp]; 
    quant_methods.fadjust    = p_Vid->AdaptiveRounding ? (&p_Vid->ARCofAdj8x8[pl][currMB->ar_mode][block_y]) : NULL;
    quant_methods.coeff_cost = coeff_cost;
    // quant_methods.pos_scan   = currMB->is_field_mode ? FIELD_SCAN8x8 : SNGL_SCAN8x8;    
    quant_methods.pos_scan   = currMB->is_field_mode ? FIELD_SCAN8x8_CAVLC : SNGL_SCAN8x8_CAVLC;    
    quant_methods.c_cost     = COEFF_COST8x8[currSlice->disthres];

    // Forward 8x8 transform
    forward8x8(mb_ores, mb_rres, block_y, block_x);

    // Quantization process
    nonzero = currSlice->quant_8x8cavlc(currMB, &mb_rres[block_y], &quant_methods, currSlice->cofAC[pl_off]);
  }

  if (nonzero)
  {
    // Inverse 8x8 transform
    inverse8x8(&mb_rres[block_y], &mb_rres[block_y], block_x);

    // generate final block
    sample_reconstruct (&img_enc[currMB->pix_y + block_y], &mb_pred[block_y], &mb_rres[block_y], block_x, currMB->pix_x + block_x, BLOCK_SIZE_8x8, BLOCK_SIZE_8x8, max_imgpel_value, DQ_BITS_8);
  }
  else // if (nonzero) => No transformed residual. Just use prediction.
  {
    copy_image_data_8x8(&img_enc[currMB->pix_y + block_y], &mb_pred[block_y], currMB->pix_x + block_x, block_x);
  }  

  //  Decoded block moved to frame memory
  return nonzero;
}
Example #25
0
 size_t read(Slice buf)
 {
     ssize_t sz = ::read(fd_, (void*) buf.data(), buf.size());
     if (sz < 0) {
         LOG_ERROR("read file " << path_ << ", error " << strerror(errno));
         return 0;
     }
     return sz;
 }
Example #26
0
bool
Ed25519::validate (Slice data) const
{
    return ed25519_sign_open (
        data.data(),
        data.size(),
        payload_.data(),
        payload_.data() + pubkey_size_) == 0;
}
Example #27
0
 static DBT to_dbt(const Slice& s)
 {
     DBT a;
     a.data = (void*) s.data();
     a.size = s.size();
     a.ulen = 0;
     a.flags = 0;
     return a;
 }
Example #28
0
SliceHash hash_value(const Slice& slice) {

	SliceHash hash = slice.getComponent()->hashValue();
	// Correct for the section offset. This is needed if we process a substack 
	// that doesn't start with the first section, but we still want globally 
	// consistant slice hashes.
	boost::hash_combine(hash, boost::hash_value(slice.getSection() + SliceHashConfiguration::sectionOffset));
	return hash;
}
Example #29
0
Block* Layout::create(size_t size)
{
    Slice buffer = alloc_aligned_buffer(size);
    if (buffer.size()) {
        return new Block(buffer, 0, 0);
    } else {
        return NULL;
    }
}
Example #30
0
 void ExpireCheck::ExpireCheckCallback(const DBID& db, const Slice& key, void* data)
 {
     ExpireCheck* e = (ExpireCheck*) data;
     ArgumentArray args;
     args.push_back("del");
     args.push_back(std::string(key.data(), key.size()));
     RedisCommandFrame cmd(args);
     e->m_server->GetMaster().FeedSlaves(NULL, db, cmd);
 }