ActionHash/lib/actionhash.rb

69 lines
2.1 KiB
Ruby
Raw Normal View History

2023-09-19 18:35:57 -06:00
# frozen_string_literal: true
require_relative 'actionhash/version'
2023-09-19 22:24:23 -06:00
require 'securerandom'
2023-09-19 18:35:57 -06:00
module ActionHash
class Error < StandardError; end
2023-09-19 22:24:23 -06:00
@key_usage_count = {}
MAX_ACTIONS_PER_KEY = 10
# Generate a new key
def self.generate_new_key
SecureRandom.hex(8)
end
2023-09-19 18:35:57 -06:00
# Create a new Action Hash
def self.create(prev_hash, input_data, key)
2023-09-19 22:24:23 -06:00
# Check if the key has reached its limit
@key_usage_count[key] ||= 0
if @key_usage_count[key] >= MAX_ACTIONS_PER_KEY
raise Error, 'Key has reached its maximum usage. Please generate a new key.'
end
2023-09-19 18:35:57 -06:00
data = [prev_hash, input_data].join(',')
2023-09-19 22:24:23 -06:00
puts "Debug: Creating hash with prev_hash=#{prev_hash}, input_data=#{input_data}, key=#{key}"
puts "Concatenated data before encryption: #{data}"
2023-09-19 18:35:57 -06:00
encrypted_data = xor_encrypt(data, key)
2023-09-19 22:24:23 -06:00
encrypted_hex = encrypted_data.unpack1('H*') # Convert to hex
puts "Encrypted hex: #{encrypted_hex}"
# Increment the usage count for the key
@key_usage_count[key] += 1
encrypted_hex
2023-09-19 18:35:57 -06:00
end
# Decrypt an Action Hash to its components
def self.down_layer(hash, key)
2023-09-19 22:24:23 -06:00
puts "Debug: Decrypting hash=#{hash} with key=#{key}"
2023-09-19 18:35:57 -06:00
hex_decoded = [hash].pack('H*') # Convert from hex
decrypted_data = xor_encrypt(hex_decoded, key)
2023-09-19 22:24:23 -06:00
puts "Decrypted data: #{decrypted_data}"
2023-09-19 18:35:57 -06:00
prev_hash, input_data = decrypted_data.split(',')
2023-09-19 22:24:23 -06:00
{ prev_hash: prev_hash.to_s, input_data: input_data.to_s }
2023-09-19 18:35:57 -06:00
end
# XOR encrypt/decrypt (symmetric)
def self.xor_encrypt(data, key)
data.bytes.zip(key.bytes.cycle).map { |a, b| (a ^ b).chr }.join
end
2023-09-19 22:24:23 -06:00
# Validate if a hash can be traced back to '0'
def self.valid_hash?(hash, key, level = 20)
current_level = 0
loop do
puts "Debug: Validating hash=#{hash} with key=#{key} at level=#{current_level}"
return false if current_level >= level
decrypted_data = down_layer(hash, key)
return true if decrypted_data[:prev_hash] == '0'
return false if decrypted_data[:prev_hash].nil? || decrypted_data[:prev_hash].empty?
hash = decrypted_data[:prev_hash]
current_level += 1
end
end
2023-09-19 18:35:57 -06:00
end