File size: 6,204 Bytes
e542d9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import gzip
import blockcypher
from flask import Flask, request, jsonify
import os
import hashlib
import binascii
import uuid
import datetime
import base64
from enum import Enum
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.backends import default_backend
from web3 import Web3
from solcx import compile_source

app = Flask(__name__)

# Blockchain and Smart Contract setup
w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:7545'))
w3.eth.default_account = w3.eth.accounts[0]

# Solidity source code
contract_source_code = '''
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract JBO3Token is ERC20 {
    constructor(uint256 initialSupply) ERC20("JBO3Token", "JBO3") {
        _mint(msg.sender, initialSupply);
    }

    function mint(address to, uint256 amount) public {
        _mint(to, amount);
    }
}
'''

# Compile the contract
compiled_sol = compile_source(contract_source_code)
contract_interface = compiled_sol['<stdin>:JBO3Token']

# Deploy the contract
JBO3 = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin'])
tx_hash = JBO3.constructor(1000000).transact()
tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
contract_address = tx_receipt.contractAddress
jbo3_contract = w3.eth.contract(address=contract_address, abi=contract_interface['abi'])

class Lap(Enum):
    PUBLIC_KEY = 1
    PRIVATE_KEY = 2
    ECDSA = 3

class CompressionAlgorithm(Enum):
    NONE = 1
    GZIP = 2

class StorageTimeline(Enum):
    PAST = 1
    PRESENT = 2
    FUTURE = 3

class Blockchain:
    def store_data(self, data):
        try:
            data_str = str(data)
            data_hash = hashlib.sha3_256(data_str.encode()).hexdigest()
            tx_hash = blockcypher.embed_data_to_blockchain(data_hash, coin_symbol='btc-testnet')
            return "Storing data in the blockchain: " + tx_hash
        except Exception as e:
            return "Error while storing data in the blockchain: " + str(e)

class SmartCard:
    def store_data(self, data):
        try:
            return "Storing data on the smart card: " + str(data)
        except Exception as e:
            return "Error while storing data on the smart card: " + str(e)

def compress_data(data, algorithm):
    if algorithm == CompressionAlgorithm.GZIP:
        compressed_data = gzip.compress(data)
        return compressed_data
    else:
        return data

@app.route('/process_files', methods=['POST'])
def process_files():
    file_paths = request.json.get('file_paths')
    compression_algorithm = CompressionAlgorithm(request.json.get('compression_algorithm'))
    storage_timeline = StorageTimeline(request.json.get('storage_timeline'))
    blockchain = Blockchain()
    smart_card = SmartCard()
    results = []

    for path in file_paths:
        try:
            with open(path, 'rb') as file:
                data = file.read()
        except FileNotFoundError:
            results.append(f"Error: File {path} not found.")
            continue
        except Exception as e:
            results.append(f"Error reading file {path}: {str(e)}")
            continue
        
        compressed_data = compress_data(data, compression_algorithm)

        for lap in Lap:
            dk = hashlib.pbkdf2_hmac('sha256', compressed_data, b'salt', 100000)
            hashed_data = binascii.hexlify(dk).decode()
            new_uuid = str(uuid.uuid4())
            timestamp = datetime.datetime.now()
            serialized_data = base64.b64encode(compressed_data)
            bitmap = list(map(int, bin(int.from_bytes(data, byteorder='big'))[2:]))
            smart_store = {'uuid': new_uuid, 'timestamp': timestamp, 'hash': hashed_data, 'bitmap': bitmap}

            if lap == Lap.PUBLIC_KEY:
                private_key = ec.generate_private_key(ec.SECP256K1(), default_backend())
                public_key = private_key.public_key()
                pem = public_key.public_bytes(
                    encoding=serialization.Encoding.PEM,
                    format=serialization.PublicFormat.SubjectPublicKeyInfo
                )
                smart_store['public_key'] = pem
            elif lap == Lap.PRIVATE_KEY:
                pem = private_key.private_bytes(
                    encoding=serialization.Encoding.PEM,
                    format=serialization.PrivateFormat.PKCS8,
                    encryption_algorithm=serialization.NoEncryption()
                )
                smart_store['private_key'] = pem
            elif lap == Lap.ECDSA:
                signature = private_key.sign(compressed_data, ec.ECDSA(hashes.SHA256()))
                smart_store['signature'] = signature

            if storage_timeline == StorageTimeline.PAST:
                result = blockchain.store_data(smart_store)
            elif storage_timeline == StorageTimeline.PRESENT:
                result = smart_card.store_data(smart_store)
            elif storage_timeline == StorageTimeline.FUTURE:
                result = "Storing data in the future"
            
            results.append(result)

    return jsonify(results)

@app.route('/mint', methods=['POST'])
def mint_tokens():
    to = request.json.get('to')
    amount = request.json.get('amount')
    tx_hash = jbo3_contract.functions.mint(to, amount).transact()
    receipt = w3.eth.waitForTransactionReceipt(tx_hash)
    return jsonify({'transactionHash': tx_hash.hex(), 'receipt': receipt})

@app.route('/transfer', methods=['POST'])
def transfer_tokens():
    from_address = request.json.get('from')
    to = request.json.get('to')
    amount = request.json.get('amount')
    tx_hash = jbo3_contract.functions.transfer(to, amount).transact({'from': from_address})
    receipt = w3.eth.waitForTransactionReceipt(tx_hash)
    return jsonify({'transactionHash': tx_hash.hex(), 'receipt': receipt})

@app.route('/balance', methods=['GET'])
def check_balance():
    address = request.args.get('address')
    balance = jbo3_contract.functions.balanceOf(address).call()
    return jsonify({'balance': balance})

if __name__ == '__main__':
    app.run(debug=True)