Esempio n. 1
0
  //-----------------------------------------------------------------------------------------------------
  bool miner::find_nonce_for_given_block(crypto::cn_context &context, Block& bl, const difficulty_type& diffic) {

    unsigned nthreads = std::thread::hardware_concurrency();

    if (nthreads > 0 && diffic > 5) {
      std::vector<std::future<void>> threads(nthreads);
      std::atomic<uint32_t> foundNonce;
      std::atomic<bool> found(false);
      uint32_t startNonce = crypto::rand<uint32_t>();

      for (unsigned i = 0; i < nthreads; ++i) {
        threads[i] = std::async(std::launch::async, [&, i]() {
          crypto::cn_context localctx;
          crypto::hash h;

          Block lb(bl); // copy to local block

          for (uint32_t nonce = startNonce + i; !found; nonce += nthreads) {
            lb.nonce = nonce;

            if (!get_block_longhash(localctx, lb, h)) {
              return;
            }

            if (check_hash(h, diffic)) {
              foundNonce = nonce;
              found = true;
              return;
            }
          }
        });
      }

      for (auto& t : threads) {
        t.wait();
      }

      if (found) {
        bl.nonce = foundNonce.load();
      }

      return found;
    } else {
      for (; bl.nonce != std::numeric_limits<uint32_t>::max(); bl.nonce++) {
        crypto::hash h;
        if (!get_block_longhash(context, bl, h)) {
          return false;
        }

        if (check_hash(h, diffic)) {
          return true;
        }
      }
    }

    return false;
  }
Esempio n. 2
0
std::string http_auth::generate_signature(const swarm::http_request &request, const std::string &key)
{
	const auto &url = request.url();
	const auto &query = url.query();
	const auto &original_headers = request.headers().all();

	std::vector<swarm::headers_entry> headers;
	for (auto it = original_headers.begin(); it != original_headers.end(); ++it) {
		std::string name = to_lower(it->first);
		if (name.compare(0, 6, "x-ell-") == 0) {
			headers.emplace_back(std::move(name), it->second);
		}
	}

	std::sort(headers.begin(), headers.end());

	std::vector<std::pair<std::string, std::string> > query_items;

	for (size_t i = 0; i < query.count(); ++i) {
		const auto &item = query.item(i);
		query_items.emplace_back(to_lower(item.first), item.second);
	}

	std::sort(query_items.begin(), query_items.end());

	swarm::url result_url;
	result_url.set_path(url.path());

	for (auto it = query_items.begin(); it != query_items.end(); ++it) {
		result_url.query().add_item(it->first, it->second);
	}

	std::string text = request.method();
	text += '\n';
	text += result_url.to_string();
	text += '\n';

	for (auto it = headers.begin(); it != headers.end(); ++it) {
		text += it->first;
		text += ':';
		text += it->second;
		text += '\n';
	}

	check_hash(key);
	check_hash(text);

	dnet_raw_id signature;
	char signature_str[DNET_ID_SIZE * 2 + 1];

	dnet_digest_auth_transform_raw(text.c_str(), text.size(), key.c_str(), key.size(), signature.id, DNET_ID_SIZE);
	dnet_dump_id_len_raw(signature.id, DNET_ID_SIZE, signature_str);

	return signature_str;
}
Esempio n. 3
0
void Miner::workerFunc(const Block& blockTemplate, difficulty_type difficulty, uint32_t nonceStep) {
  try {
    Block block = blockTemplate;
    Crypto::cn_context cryptoContext;

    while (m_state == MiningState::MINING_IN_PROGRESS) {
      Crypto::Hash hash;
      if (!get_block_longhash(cryptoContext, block, hash)) {
        //error occured
        m_logger(Logging::DEBUGGING) << "calculating long hash error occured";
        m_state = MiningState::MINING_STOPPED;
        return;
      }

      if (check_hash(hash, difficulty)) {
        m_logger(Logging::INFO) << "Found block for difficulty " << difficulty;

        if (!setStateBlockFound()) {
          m_logger(Logging::DEBUGGING) << "block is already found or mining stopped";
          return;
        }

        m_block = block;
        return;
      }

      block.nonce += nonceStep;
    }
  } catch (std::exception& e) {
    m_logger(Logging::ERROR) << "Miner got error: " << e.what();
    m_state = MiningState::MINING_STOPPED;
  }
}
Esempio n. 4
0
static bool checkWord(char * start, int length, const char * const hash, bool caseSensitive)
{
	if (caseSensitive && length <= MAX_SIZE_CASE_INSENSITIVE)
		return checkWord_internal(start, start, length, hash);
	else
		return check_hash(start, hash);
}
Esempio n. 5
0
  bool Currency::checkProofOfWork(crypto::cn_context& context, const Block& block, difficulty_type currentDiffic, crypto::hash& proofOfWork) const {
    if (!get_block_longhash(context, block, proofOfWork)) {
      return false;
    }

    return check_hash(proofOfWork, currentDiffic);
  }
Esempio n. 6
0
static void
check_sector(struct tfilter *filter, int type, int rw, uint64_t sec, char *buf)
{
	if (sec >= filter->secs)
		return;

	if (rw) {
		if (type == PRE_CHECK)
			insert_hash(filter, sec, buf);
		else
			check_hash(filter, sec, buf, WRITE_INTEGRITY);
	} else if (type == POST_CHECK) {
		check_hash(filter, sec, buf, READ_INTEGRITY);
		insert_hash(filter, sec, buf);
	}
}
Esempio n. 7
0
static void run_py_test(const char * const json, const char * const h) {
  hash r;
  python_json_hash(json, r);

  hash e;
  a_to_hash(h, e);

  check_hash(e, r);
}
Esempio n. 8
0
File: main.c Progetto: Azii/Uni
/*
Calculates Blockhashes in a simple loop.
*/
int bitcoin_simple() {
	printf("Starting bitcoin_simple\n");
	// Start, end time
	unsigned long start,end;
	// Set start time
	start = current_time_millis();


	// Creates and retrieves the Block-Header information
	Blockheader * blockheader = malloc(sizeof(Blockheader));
	// The getWork method fills an empty Blockheader struct with all the neccesary information needed to calcualte the Hash of a Block.
	getWork(blockheader);
	// The nonce is the value that is incremented in each run to get a different hash value
	char * n = malloc(sizeof(char)*4);
	memcpy(n,&(blockheader->nonce),sizeof(char)*4);
	// The values in the Blockheader are actually in reverse byte order and need to be reversed in order to increment the nonce value. 
	byte_reversal(n,sizeof(char)*4);
	// Convert the 4 byte long raw data into an unsinged long 
	unsigned long starting_nonce = n[0] << 24 | n[1] << 16 | n[2] << 8 | n[3];
	// The nonce value we received in the getWork method is the actual starting nonce value. We start to calculate hashes with this initial nonce and increase it by one in each run. 
	unsigned long nonce = starting_nonce;
	char * hash;
	// In practice it is very hard to find a valid hash, so in this exercise we will limit the amount of hashes we calculate.
	for(;nonce<=(starting_nonce+MAX_HASHES);nonce++) {
		// put current nonce in blockheader object
		// first, shift long back to char[4]
		n[0] = nonce >> 24;
		n[1] = nonce >> 16;
		n[2] = nonce >> 8;
		n[3] = nonce;
		// reverse byte order
		byte_reversal(n,sizeof(char)*4);
		// put n into blockheader
		blockheader->nonce[0] = n[0];
		blockheader->nonce[1] = n[1];
		blockheader->nonce[2] = n[2];
		blockheader->nonce[3] = n[3];
		// calculate the hash using the sha-256 hashing algorithm
		size_t size = getData(blockheader,&hash);
		size = sha256_digest(hash,size,&hash);
		// To calculate a valid hash, we need to do two hashing passes
		size = sha256_digest(hash,size,&hash);
		if(check_hash(hash,(int)size))
		{
			printf("%ld : ", nonce);
			print_hash(hash,size);
		}
	}

	end = current_time_millis();
	printf("Calculation finished after %.3fs\n", (double) (end - start) / 1000);

	free(blockheader);
	return EXIT_SUCCESS;

}
Esempio n. 9
0
/* This function checks the validity of a hashed field (e.g. from). 'type' is
 * the type of the field to validate (subpacket type), 'data' is the data to
 * validate against the hash in the KSP, 'len' the length of the data.
 * This function sets the KMO error string. It returns -1 on failure.
 */
int kmocrypt_signature_check_hash2(struct kmocrypt_signature2 *self, int type, unsigned char *data, uint32_t len) {
    assert(type < KMO_SP_NB_TYPE && subpackets_ops[type].recognize == recognize_hash);

    if (! self->subpacket_array[type]) {
        kmo_seterror("unavailable type %d in KSP", type);
        return -1;
    }

    return check_hash(self, self->subpacket_array[type]->data, data, len);
}
BlockchainTransactions::BlockchainTransactions(
    const opentxs::api::storage::Driver& storage,
    const std::string& hash)
    : Node(storage, hash)
{
    if (check_hash(hash)) {
        init(hash);
    } else {
        version_ = CURRENT_VERSION;
        root_ = Node::BLANK_HASH;
    }
}
Esempio n. 11
0
static bool checkWord_internal(const char * const start, char * current, int length, const char * const hash)
{
	if (length == 0) {
		return check_hash(start, hash);
	}

	char c = *current;
	*current = switchCase(*current);
	if (checkWord_internal(start, current + sizeof(char), length - 1, hash))
		return true;

	*current = c;
	return checkWord_internal(start, current + sizeof(char), length - 1, hash);
}
Esempio n. 12
0
static void
check_page_labels (fz_context *ctx, pdfout_data *labels)
{
  int len = pdfout_data_array_len (ctx, labels);
  if (len < 1)
    pdfout_throw (ctx, "empty page labels");
  
  int previous_page = 0;
  for (int i = 0; i < len; ++i)
    {
      pdfout_data *hash = pdfout_data_array_get (ctx, labels, i);
      previous_page = check_hash (ctx, hash, previous_page);
    }
  
}
Esempio n. 13
0
int metalink_check_hash(struct GlobalConfig *config,
                        metalinkfile *mlfile,
                        const char *filename)
{
  int rv;
  fprintf(config->errors, "Metalink: validating (%s)...\n", filename);
  if(mlfile->checksum == NULL) {
    fprintf(config->errors,
            "Metalink: validating (%s) FAILED (digest missing)\n", filename);
    return -2;
  }
  rv = check_hash(filename, mlfile->checksum->digest_def,
                  mlfile->checksum->digest, config->errors);
  return rv;
}
proto::StorageBlockchainTransactions BlockchainTransactions::serialize() const
{
    proto::StorageBlockchainTransactions serialized{};
    serialized.set_version(version_);

    for (const auto item : item_map_) {
        const bool goodID = !item.first.empty();
        const bool goodHash = check_hash(std::get<0>(item.second));
        const bool good = goodID && goodHash;

        if (good) {
            serialize_index(
                item.first, item.second, *serialized.add_transaction());
        }
    }

    return serialized;
}
Esempio n. 15
0
void predexp_node_2_as_predexp(as_predexp_array *a, VALUE node) {
  check_hash(node);

  // node = {
  //   bin: bin,
  //   true: true,
  //   filters: {
  //     filter: :eq,
  //     value: 1
  //   },
  //   and: [],
  //   or: []
  // }

  VALUE node_bin = rb_hash_aref(node, bin_sym);

  VALUE node_true = rb_hash_aref(node, predexp_true_sym);
  VALUE node_filters = rb_hash_aref(node, predexp_filters_sym);
  push_2_as_predexp(a, node_bin, node_true, node_filters);

  VALUE node_and = rb_hash_aref(node, predexp_and_sym);
  check_array(node_and);
  int length = rb_ary_len_int(node_and);
  if (length > 0) {
    for(int i = 0; i < length; i++){
      VALUE node_and_obj = rb_ary_entry(node_and, i);
      predexp_node_2_as_predexp(a, node_and_obj);
    }
    insert_as_predexp_array(a, as_predexp_and(length + 1));
  }

  VALUE node_or = rb_hash_aref(node, predexp_or_sym);
  check_array(node_or);
  length = rb_ary_len_int(node_or);
  if (length > 0) {
    for(int i = 0; i < length; i++){
      VALUE node_or_obj = rb_ary_entry(node_or, i);
      predexp_node_2_as_predexp(a, node_or_obj);
    }
    insert_as_predexp_array(a, as_predexp_or(length + 1));
  }
}
Esempio n. 16
0
/**
 * Returns TRUE if the checksum was changed for associated
 * path and send an alert warning.
 * Returns FALSE if the checksum is the same or not defined
 * for this service.
 */
static int check_checksum(Service_T s, char *report) {

  ASSERT(s);

  if(!s->checksum)
    return FALSE;

  if( !check_hash(s->path, s->checksum->hash, s->checksum->type) ) {
    snprintf(report, STRLEN, "checksum test failed for %s", s->path);
    /* Set the old checksum to the new value so we do not report this
     * more than once per change */
    FREE(s->checksum->hash);
    s->checksum->hash= get_checksum(s->path, s->checksum->type);
    return TRUE;
  }
  
  DEBUG("'%s' has valid checksums\n", s->name);
  
  return FALSE;

}
Esempio n. 17
0
static bool findText_internal(const char * const start, char * const current, const int length, const unsigned char * const hash)
{
	if (length == 0)
		return check_hash(start, hash);
	
	char c;
	
	for (c = 'a'; c <= 'z'; c++) {
		*current = c;
		if (findText_internal(start, current + sizeof(char), length - 1, hash))
			return true;
	}
	
	for (c = 'A'; c <= 'Z'; c++) {
		*current = c;
		if (findText_internal(start, current + sizeof(char), length - 1, hash))
			return true;
	}
	
	return false;
}
Esempio n. 18
0
int do_hash(char *algo, char *word)
{
	unsigned char hash[64 + 1], seed[10];
	double tm;
	int iterations = 0;
	clock_t cstart = clock(), cend = 0;

	srandom(time(NULL));
	memset(&hash, 0, sizeof hash);

	unsigned long r[NUM_THREADS] = {0};
	pthread_t thread[NUM_THREADS];

	int i;
	for(i = 0; i < NUM_THREADS; i++){
		r[i] = random()^i;
//		printf("Thread number %d, r = %lu, ", i, r[i]); //DEBUG
//		printf("created at 0x%08lx\n", (unsigned long) &thread[i]); //DEBUG
	}
//	return 0; //DEBUG

	if(!strncmp(algo, "md5", 3)){
		for(;;){
			iterations++;
			sprintf(seed, "%lu", random());
			MD5(seed, sizeof seed, hash);
			//output_hash(hash, algo); //DEBUG
			if(check_hash(hash, word))
				break;
		}
	}
	else if(!strncmp(algo, "sha1", 4)){
		for(;;){
			iterations++;
			sprintf(seed, "%lu", random());
			SHA1(seed, sizeof seed, hash);
			//output_hash(hash, algo); //DEBUG
			if(check_hash(hash, word)){
				break;
			}
		}
	}
	else if(!strncmp(algo, "sha256", 6)){
		for(;;){
			iterations++;
			sprintf(seed, "%lu", random());
			SHA256(seed, sizeof seed, hash);
			//output_hash(hash, algo); //DEBUG
			if(check_hash(hash, word)){
				break;
			}
		}
	}
	else if(!strncmp(algo, "sha384", 6)){
		for(;;){
			iterations++;
			sprintf(seed, "%lu", random());
			SHA384(seed, sizeof seed, hash);
			//output_hash(hash, algo); //DEBUG
			if(check_hash(hash, word)){
				break;
			}
		}
	}
	else if(!strncmp(algo, "sha512", 6)){
		for(;;){
			iterations++;
			sprintf(seed, "%lu", random());
			SHA512(seed, sizeof seed, hash);
			//output_hash(hash, algo); //DEBUG
			if(check_hash(hash, word)){
				break;
			}
		}
	}
	else if(!strncmp(algo, "rmd160", 6)){
		for(;;){
			iterations++;
			sprintf(seed, "%lu", random());
			RIPEMD160(seed, sizeof seed, hash);
			//output_hash(hash, algo); //DEBUG
			if(check_hash(hash, word)){
				break;
			}
		}
	}
	else {
		printf("Unknown hashing algorithm.\n\n");
		return 1;
	}

	cend = clock();
        tm = ((double)cend - (double)cstart) * 1.0e-6;

	printf("String match found in %.3f seconds. (%d iterations)\nHASH: ", tm, iterations);
	output_hash(hash, algo);
	printf("SEED: %s\n\n", seed);
	return 0;
}
Esempio n. 19
0
int check_cracked (hashcat_ctx_t *hashcat_ctx, hc_device_param_t *device_param, const u32 salt_pos)
{
  cpt_ctx_t      *cpt_ctx      = hashcat_ctx->cpt_ctx;
  hashconfig_t   *hashconfig   = hashcat_ctx->hashconfig;
  hashes_t       *hashes       = hashcat_ctx->hashes;
  status_ctx_t   *status_ctx   = hashcat_ctx->status_ctx;
  user_options_t *user_options = hashcat_ctx->user_options;

  salt_t *salt_buf = &hashes->salts_buf[salt_pos];

  u32 num_cracked;

  cl_int CL_err;

  CL_err = hc_clEnqueueReadBuffer (hashcat_ctx, device_param->command_queue, device_param->d_result, CL_TRUE, 0, sizeof (u32), &num_cracked, 0, NULL, NULL);

  if (CL_err != CL_SUCCESS)
  {
    event_log_error (hashcat_ctx, "clEnqueueReadBuffer(): %s", val2cstr_cl (CL_err));

    return -1;
  }

  if (user_options->speed_only == true)
  {
    // we want the hc_clEnqueueReadBuffer to run in benchmark mode because it has an influence in performance
    // however if the benchmark cracks the artificial hash used for benchmarks we don't want to see that!

    return 0;
  }

  if (num_cracked)
  {
    plain_t *cracked = (plain_t *) hccalloc (num_cracked, sizeof (plain_t));

    CL_err = hc_clEnqueueReadBuffer (hashcat_ctx, device_param->command_queue, device_param->d_plain_bufs, CL_TRUE, 0, num_cracked * sizeof (plain_t), cracked, 0, NULL, NULL);

    if (CL_err != CL_SUCCESS)
    {
      event_log_error (hashcat_ctx, "clEnqueueReadBuffer(): %s", val2cstr_cl (CL_err));

      return -1;
    }

    u32 cpt_cracked = 0;

    hc_thread_mutex_lock (status_ctx->mux_display);

    for (u32 i = 0; i < num_cracked; i++)
    {
      const u32 hash_pos = cracked[i].hash_pos;

      if (hashes->digests_shown[hash_pos] == 1) continue;

      if ((hashconfig->opts_type & OPTS_TYPE_PT_NEVERCRACK) == 0)
      {
        hashes->digests_shown[hash_pos] = 1;

        hashes->digests_done++;

        cpt_cracked++;

        salt_buf->digests_done++;

        if (salt_buf->digests_done == salt_buf->digests_cnt)
        {
          hashes->salts_shown[salt_pos] = 1;

          hashes->salts_done++;
        }
      }

      if (hashes->salts_done == hashes->salts_cnt) mycracked (hashcat_ctx);

      check_hash (hashcat_ctx, device_param, &cracked[i]);
    }

    hc_thread_mutex_unlock (status_ctx->mux_display);

    hcfree (cracked);

    if (cpt_cracked > 0)
    {
      hc_thread_mutex_lock (status_ctx->mux_display);

      cpt_ctx->cpt_buf[cpt_ctx->cpt_pos].timestamp = time (NULL);
      cpt_ctx->cpt_buf[cpt_ctx->cpt_pos].cracked   = cpt_cracked;

      cpt_ctx->cpt_pos++;

      cpt_ctx->cpt_total += cpt_cracked;

      if (cpt_ctx->cpt_pos == CPT_CACHE) cpt_ctx->cpt_pos = 0;

      hc_thread_mutex_unlock (status_ctx->mux_display);
    }

    if (hashconfig->opts_type & OPTS_TYPE_PT_NEVERCRACK)
    {
      // we need to reset cracked state on the device
      // otherwise host thinks again and again the hash was cracked
      // and returns invalid password each time

      memset (hashes->digests_shown_tmp, 0, salt_buf->digests_cnt * sizeof (u32));

      CL_err = hc_clEnqueueWriteBuffer (hashcat_ctx, device_param->command_queue, device_param->d_digests_shown, CL_TRUE, salt_buf->digests_offset * sizeof (u32), salt_buf->digests_cnt * sizeof (u32), &hashes->digests_shown_tmp[salt_buf->digests_offset], 0, NULL, NULL);

      if (CL_err != CL_SUCCESS)
      {
        event_log_error (hashcat_ctx, "clEnqueueWriteBuffer(): %s", val2cstr_cl (CL_err));

        return -1;
      }
    }

    num_cracked = 0;

    CL_err = hc_clEnqueueWriteBuffer (hashcat_ctx, device_param->command_queue, device_param->d_result, CL_TRUE, 0, sizeof (u32), &num_cracked, 0, NULL, NULL);

    if (CL_err != CL_SUCCESS)
    {
      event_log_error (hashcat_ctx, "clEnqueueWriteBuffer(): %s", val2cstr_cl (CL_err));

      return -1;
    }
  }

  return 0;
}
Esempio n. 20
0
  //-----------------------------------------------------------------------------------------------------
  bool miner::worker_thread(uint32_t th_local_index)
  {
    logger(INFO) << "Miner thread was started ["<< th_local_index << "]";
    uint32_t nonce = m_starter_nonce + th_local_index;
    difficulty_type local_diff = 0;
    uint32_t local_template_ver = 0;
    crypto::cn_context context;
    Block b;

    while(!m_stop)
    {
      if(m_pausers_count) //anti split workaround
      {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
        continue;
      }

      if(local_template_ver != m_template_no) {
        std::unique_lock<std::mutex> lk(m_template_lock);
        b = m_template;
        local_diff = m_diffic;
        lk.unlock();

        local_template_ver = m_template_no;
        nonce = m_starter_nonce + th_local_index;
      }

      if(!local_template_ver)//no any set_block_template call
      {
        logger(TRACE) << "Block template not set yet";
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        continue;
      }

      b.nonce = nonce;
      crypto::hash h;
      if (!m_stop && !get_block_longhash(context, b, h)) {
        logger(ERROR) << "Failed to get block long hash";
        m_stop = true;
      }

      if (!m_stop && check_hash(h, local_diff))
      {
        //we lucky!
        ++m_config.current_extra_message_index;

        logger(INFO, GREEN) << "Found block for difficulty: " << local_diff;

        if(!m_handler.handle_block_found(b)) {
          --m_config.current_extra_message_index;
        } else {
          //success update, lets update config
          Common::saveStringToFile(m_config_folder_path + "/" + CryptoNote::parameters::MINER_CONFIG_FILE_NAME, storeToJson(m_config));
        }
      }

      nonce += m_threads_total;
      ++m_hashes;
    }
    logger(INFO) << "Miner thread stopped ["<< th_local_index << "]";
    return true;
  }
Esempio n. 21
0
void push_2_as_predexp(as_predexp_array *a, VALUE node_bin, VALUE node_true, VALUE node_filters){
  check_hash(node_filters);
  VALUE bin;

  switch(TYPE(node_bin)){
    case T_STRING:
      bin = StringValueCStr(node_bin);
      break;
    case T_SYMBOL:
      if(node_bin != predexp_record_sym) {
        node_bin = rb_funcall(node_bin, rb_intern("to_s"), 0);
        bin      = StringValueCStr(node_bin);
      }
      break;
    default:
      raise_parse_error();
      break;
  }

  VALUE node_filter = rb_hash_aref(node_filters, predexp_filter_sym);
  VALUE node_collection = rb_hash_aref(node_filters, predexp_collection_sym);
  VALUE node_value = rb_hash_aref(node_filters, value_sym);
  VALUE node_value_type = TYPE(node_value);

  if (node_bin == predexp_record_sym){
    VALUE record_filter = rb_hash_aref(node_filters, predexp_record_filter_sym);
    if(record_filter ==  predexp_record_last_update_sym) {
      insert_as_predexp_array(a, as_predexp_rec_last_update());
    } else if (record_filter == predexp_record_expiration_time_sym) {
      insert_as_predexp_array(a, as_predexp_rec_void_time());
    } else {
      raise_parse_error();
    }
    node_value = NUM2ULONG(node_value);
    insert_as_predexp_array(a, as_predexp_integer_value(node_value));
    insert_integer_predicate(a, node_filter);

  } else if(node_collection != Qnil) {
    VALUE node_collection_pred = rb_hash_aref(node_filters, predexp_collection_pred_sym);
    VALUE node_collection_var = rb_hash_aref(node_filters, predexp_collection_var_sym);
    if (node_collection_pred == Qnil || node_collection_var == Qnil) {
      raise_parse_error();
    } else if(node_value_type == T_FIXNUM) {
      node_value = NUM2UINT(node_value);
      insert_as_predexp_array(a, as_predexp_integer_var(node_collection_var));
      insert_as_predexp_array(a, as_predexp_integer_value(node_value));
      insert_integer_predicate(a, node_filter);
      insert_collection_predicate(a, bin, node_collection, node_collection_pred, node_collection_var);
    } else if(node_value_type == T_STRING) {
      node_value = StringValueCStr(node_value);
      insert_as_predexp_array(a, as_predexp_string_var(node_collection_var));
      insert_as_predexp_array(a, as_predexp_string_value(node_value));
      if (node_filter == predexp_equal_sym) {
        insert_as_predexp_array(a, as_predexp_string_equal());
      } else if(node_filter == predexp_unequal_sym) {
        insert_as_predexp_array(a, as_predexp_string_unequal());
      } else if(node_filter == predexp_regexp_sym) {
        insert_as_predexp_array(a, as_predexp_string_regex(1));
      } else {
        raise_parse_error();
      }
    } else if(node_value_type == T_DATA) {
      if ( rb_funcall(node_value, rb_intern("is_a?"), 1, rb_aero_GeoJson) == Qtrue ) {
        as_geojson * geo = get_geo_json_struct(node_value);
        char * buffer = (char *) malloc ( strlen(geo->value) + 1 );
        strcpy(buffer, geo->value);
        insert_as_predexp_array(a, as_predexp_geojson_var(node_collection_var));
        insert_as_predexp_array(a, as_predexp_geojson_value(buffer));
        if (node_filter == predexp_within_sym) {
          insert_as_predexp_array(a, as_predexp_geojson_within());
        } else if(node_filter == predexp_contains_sym) {
          insert_as_predexp_array(a, as_predexp_geojson_contains());
        } else {
          raise_parse_error();
        }
      } else {
        raise_parse_error();
      }
    } else {
      raise_parse_error();
    }
    insert_collection_predicate(a, bin, node_collection, node_collection_pred, node_collection_var);

  } else if(node_value_type == T_FIXNUM){
    node_value = NUM2UINT(node_value);
    insert_as_predexp_array(a, as_predexp_integer_bin(bin));
    insert_as_predexp_array(a, as_predexp_integer_value(node_value));
    insert_integer_predicate(a, node_filter);

  } else if(node_value_type == T_STRING){
    node_value = StringValueCStr(node_value);
    insert_as_predexp_array(a, as_predexp_string_bin(bin));
    insert_as_predexp_array(a, as_predexp_string_value(node_value));
    if (node_filter == predexp_equal_sym) {
      insert_as_predexp_array(a, as_predexp_string_equal());
    } else if(node_filter == predexp_unequal_sym) {
      insert_as_predexp_array(a, as_predexp_string_unequal());
    } else if(node_filter == predexp_regexp_sym) {
      insert_as_predexp_array(a, as_predexp_string_regex(1));
    } else {
      raise_parse_error();
    }
  } else if(node_value_type == T_DATA){
    if ( rb_funcall(node_value, rb_intern("is_a?"), 1, rb_aero_GeoJson) == Qtrue ) {
      as_geojson * geo = get_geo_json_struct(node_value);
      char * buffer = (char *) malloc ( strlen(geo->value) + 1 );
      strcpy(buffer, geo->value);
      insert_as_predexp_array(a, as_predexp_geojson_bin(bin));
      insert_as_predexp_array(a, as_predexp_geojson_value(buffer));
      if (node_filter == predexp_within_sym) {
        insert_as_predexp_array(a, as_predexp_geojson_within());
      } else if(node_filter == predexp_contains_sym) {
        insert_as_predexp_array(a, as_predexp_geojson_contains());
      } else {
        raise_parse_error();
      }
    } else {
      raise_parse_error();
    }
  } else {
    raise_parse_error();
  }

  if(node_true == Qfalse) {
    insert_as_predexp_array(a, as_predexp_not(1));
  }
}
Esempio n. 22
0
/*
 * If there is a mismatch or an error, then gda_connection_add_event_string() is used
 *
 *  - Modifies @sbuffer (to separate HASH from XML part)
 *  - if all OK, extracs the <challenge> value and replace cdata->next_challenge with it (or simply
 *    reset cdata->next_challenge to NULL)
 *
 * Returns: a new #xmlDocPtr, or %NULL on error
 */
static xmlDocPtr
decode_buffer_response (GdaConnection *cnc, WebConnectionData *cdata, SoupBuffer *sbuffer,
			gchar *out_status_chr, guint *out_counter_id)
{
	xmlDocPtr doc;
	gchar *ptr, *response;

	if (out_status_chr)
		*out_status_chr = 0;
	if (out_counter_id)
		*out_counter_id = 0;

	g_assert (sbuffer);
	response = (gchar*) sbuffer->data;

	for (ptr = response; *ptr && (*ptr != '\n'); ptr++);
	if (*ptr != '\n') {
		gda_connection_add_event_string (cnc, _("Could not parse server's reponse"));
		return NULL;
	}
	*ptr = 0;
	ptr++;

	if ((cdata->key && !check_hash (cdata->key, ptr, response)) &&
	    (cdata->server_secret && !check_hash (cdata->server_secret, ptr, response))) {
		gda_connection_add_event_string (cnc, _("Invalid response hash"));
		return NULL;
	}
	doc = xmlParseMemory (ptr, strlen (ptr));

	if (!doc) {
		gda_connection_add_event_string (cnc, _("Could not parse server's reponse"));
		return NULL;
	}
	else {
		xmlNodePtr node, root;

		root = xmlDocGetRootElement (doc);
		for (node = root->children; node; node = node->next) {
			if (!strcmp ((gchar*) node->name, "session")) {
				xmlChar *contents;
				contents = xmlNodeGetContent (node);
				g_free (cdata->session_id);
				cdata->session_id = g_strdup ((gchar*) contents);
				xmlFree (contents);
			}
			else if (!strcmp ((gchar*) node->name, "challenge")) {
				xmlChar *contents;
				if (cdata->next_challenge) {
					g_free (cdata->next_challenge);
					cdata->next_challenge = NULL;
				}
				contents = xmlNodeGetContent (node);
				cdata->next_challenge = g_strdup ((gchar*) contents);
				xmlFree (contents);
			}
			else if (out_status_chr && !strcmp ((gchar*) node->name, "status")) {
				xmlChar *contents;
				contents = xmlNodeGetContent (node);
				*out_status_chr = *contents;
				xmlFree (contents);
			}
			else if (out_counter_id && !strcmp ((gchar*) node->name, "counter")) {
				xmlChar *contents;
				contents = xmlNodeGetContent (node);
				*out_counter_id = atoi ((gchar*) contents);
				xmlFree (contents);
			}
			else if (!cdata->server_id && !strcmp ((gchar*) node->name, "servertype")) {
				xmlChar *contents;
				contents = xmlNodeGetContent (node);
				cdata->server_id = g_strdup ((gchar*) contents);
				xmlFree (contents);

				cdata->reuseable = _gda_provider_reuseable_new (cdata->server_id);
#ifdef DEBUG_WEB_PROV
				g_print ("REUSEABLE [%s]: %p\n", cdata->server_id, cdata->reuseable);
#endif
			}
			else if (!cdata->server_version && !strcmp ((gchar*) node->name, "serverversion")) {
				xmlChar *contents;
				contents = xmlNodeGetContent (node);
				cdata->server_version = g_strdup ((gchar*) contents);
				xmlFree (contents);
#ifdef DEBUG_WEB_PROV
				g_print ("SERVER version [%s]\n", cdata->server_version);
#endif
			}
		}
	}

	return doc;
}
Esempio n. 23
0
File: main.c Progetto: Azii/Uni
int calculate_hash(Blockheader * blockheader, int num_hashes)
{
	unsigned char * n = malloc(sizeof(char) * 4);
	memcpy(n, blockheader->nonce, sizeof(char) * 4);
	byte_reversal(n, sizeof(char) * 4);
	
	unsigned long starting_nonce = n[0] << 24 | n[1] << 16 | n[2] << 8 | n[3];
	unsigned long end_nonce = starting_nonce + num_hashes;
	unsigned long nonce = starting_nonce;
	//printf("starting_nonce: %ld\n", starting_nonce);
	
	// copy paste
	for( ; nonce <= end_nonce; nonce++) {
		// put current nonce in blockheader object
		// first, shift long back to char[4]
		n[0] = nonce >> 24;
		n[1] = nonce >> 16;
		n[2] = nonce >> 8;
		n[3] = nonce;
		// reverse byte order
		byte_reversal(n,sizeof(char)*4);
		// put n into blockheader
		blockheader->nonce[0] = n[0];
		blockheader->nonce[1] = n[1];
		blockheader->nonce[2] = n[2];
		blockheader->nonce[3] = n[3];
		//printf("blockheader->nonce val after assignment in for loop: %ld\n", toulong(blockheader->nonce));
		// calculate the hash using the sha-256 hashing algorithm
		char * hash;
		size_t size = getData(blockheader,&hash);
		char * r1;
		size = sha256_digest(hash,size,&r1);
		free(hash);
		// To calculate a valid hash, we need to do two hashing passes
		char * r2;
		size = sha256_digest(r1,size,&r2);
		free(r1);
		if(check_hash(r2,(int)size))
		{
			printf("%ld : ", nonce);
			print_hash(r2,size);
		}
		free(r2);
		
	}
	
	//printf("blockheader->nonce val after for loop: %ld", toulong(blockheader->nonce));
	
	unsigned char * end_nonce_char = to_reversed_char_arr(end_nonce - 1);
	//memcpy(&(blockheader->nonce), end_nonce_char, sizeof(char) * 4);
	blockheader->nonce[0] = end_nonce_char[0];
	blockheader->nonce[1] = end_nonce_char[1];
	blockheader->nonce[2] = end_nonce_char[2];
	blockheader->nonce[3] = end_nonce_char[3];
	
	//printf("blockheader nonce end of calc hash function: %ld\n", toulong(blockheader->nonce));
	
	free(n);
	
	return EXIT_SUCCESS;
}