├── server ├── medical-records │ └── .gitkeep ├── .eslintrc ├── .gitignore ├── package.json └── server.js ├── client ├── public │ ├── robots.txt │ ├── favicon.ico │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── index.html ├── .eslintrc ├── src │ ├── helpers │ │ └── users.js │ ├── App.test.js │ ├── App.css │ ├── index.css │ ├── index.js │ ├── components │ │ ├── DoctorsList.jsx │ │ ├── PatientsOverview.jsx │ │ ├── DoctorView.jsx │ │ ├── DoctorsAccessButton.jsx │ │ ├── PatientMedicalRecordsList.jsx │ │ ├── LogInOrRegister.jsx │ │ └── PatientView.jsx │ ├── getWeb3.js │ ├── App.jsx │ ├── serviceWorker.js │ └── logo.svg ├── .gitignore ├── package.json └── README.md ├── copy-contracts-to-server.ps1 ├── images ├── doctor_view.jpg └── patient_view.jpg ├── migrations ├── 1_initial_migration.js └── 2_deploy_contracts.js ├── truffle-config.js ├── test ├── TestSimpleStorage.sol └── simplestorage.js ├── contracts ├── Migrations.sol └── Healthchain.sol ├── LICENSE └── README.md /server/medical-records/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /server/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "babel-eslint" 3 | } -------------------------------------------------------------------------------- /server/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | contracts 3 | medical-records -------------------------------------------------------------------------------- /client/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | -------------------------------------------------------------------------------- /copy-contracts-to-server.ps1: -------------------------------------------------------------------------------- 1 | rm -r server/contracts 2 | cp -r client/src/contracts server/contracts -------------------------------------------------------------------------------- /images/doctor_view.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eddex/healthchain/HEAD/images/doctor_view.jpg -------------------------------------------------------------------------------- /client/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eddex/healthchain/HEAD/client/public/favicon.ico -------------------------------------------------------------------------------- /client/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eddex/healthchain/HEAD/client/public/logo192.png -------------------------------------------------------------------------------- /client/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eddex/healthchain/HEAD/client/public/logo512.png -------------------------------------------------------------------------------- /images/patient_view.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/eddex/healthchain/HEAD/images/patient_view.jpg -------------------------------------------------------------------------------- /client/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "babel-eslint", 3 | "plugins": [ 4 | "react" 5 | ] 6 | } -------------------------------------------------------------------------------- /migrations/1_initial_migration.js: -------------------------------------------------------------------------------- 1 | var Migrations = artifacts.require("./Migrations.sol"); 2 | 3 | module.exports = function(deployer) { 4 | deployer.deploy(Migrations); 5 | }; 6 | -------------------------------------------------------------------------------- /migrations/2_deploy_contracts.js: -------------------------------------------------------------------------------- 1 | var Healthchain = artifacts.require("./Healthchain.sol"); 2 | 3 | module.exports = function(deployer) { 4 | deployer.deploy(Healthchain); 5 | }; 6 | -------------------------------------------------------------------------------- /client/src/helpers/users.js: -------------------------------------------------------------------------------- 1 | export const doctors = [ 2 | { account: 1, name: 'Dr. Debug' }, 3 | { account: 2, name: 'Dr. Dumbledore' } 4 | ] 5 | 6 | export const patients = [ 7 | { account: 3, name: 'Mr. Bitcoin' }, 8 | { account: 4, name: 'Mrs. Blockchain' } 9 | ] -------------------------------------------------------------------------------- /client/src/App.test.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | 5 | it('renders without crashing', () => { 6 | const div = document.createElement('div'); 7 | ReactDOM.render(, div); 8 | ReactDOM.unmountComponentAtNode(div); 9 | }); 10 | -------------------------------------------------------------------------------- /truffle-config.js: -------------------------------------------------------------------------------- 1 | const path = require("path"); 2 | 3 | module.exports = { 4 | // See 5 | // to customize your Truffle configuration! 6 | contracts_build_directory: path.join(__dirname, "client/src/contracts"), 7 | networks: { 8 | develop: { 9 | port: 7545 10 | } 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /client/src/App.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | height: 100%; 3 | background-image: linear-gradient(to bottom right, #007427, #00d447); 4 | } 5 | 6 | .App { 7 | margin: 1rem; 8 | } 9 | 10 | .card-body { 11 | padding: 1rem; 12 | } 13 | 14 | .header-icon { 15 | font-size: 2rem; 16 | margin-right: 0.5rem; 17 | } 18 | 19 | .debug-buttons { 20 | margin-bottom: 1rem; 21 | margin-right: 0.3rem; 22 | } 23 | -------------------------------------------------------------------------------- /client/src/index.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", 4 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", 5 | sans-serif; 6 | -webkit-font-smoothing: antialiased; 7 | -moz-osx-font-smoothing: grayscale; 8 | } 9 | 10 | code { 11 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", 12 | monospace; 13 | } 14 | -------------------------------------------------------------------------------- /client/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | src/contracts 8 | 9 | # testing 10 | /coverage 11 | 12 | # production 13 | /build 14 | 15 | # misc 16 | .DS_Store 17 | .env.local 18 | .env.development.local 19 | .env.test.local 20 | .env.production.local 21 | 22 | npm-debug.log* 23 | yarn-debug.log* 24 | yarn-error.log* 25 | -------------------------------------------------------------------------------- /client/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import './index.css'; 4 | import App from './App'; 5 | import * as serviceWorker from './serviceWorker'; 6 | 7 | ReactDOM.render(, document.getElementById('root')); 8 | 9 | // If you want your app to work offline and load faster, you can change 10 | // unregister() to register() below. Note this comes with some pitfalls. 11 | // Learn more about service workers: https://bit.ly/CRA-PWA 12 | serviceWorker.unregister(); 13 | -------------------------------------------------------------------------------- /test/TestSimpleStorage.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.5.0; 2 | 3 | import "truffle/Assert.sol"; 4 | import "truffle/DeployedAddresses.sol"; 5 | import "../contracts/SimpleStorage.sol"; 6 | 7 | contract TestSimpleStorage { 8 | 9 | function testItStoresAValue() public { 10 | SimpleStorage simpleStorage = SimpleStorage(DeployedAddresses.SimpleStorage()); 11 | 12 | simpleStorage.set(89); 13 | 14 | uint expected = 89; 15 | 16 | Assert.equal(simpleStorage.get(), expected, "It should store the value 89."); 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /test/simplestorage.js: -------------------------------------------------------------------------------- 1 | const SimpleStorage = artifacts.require("./SimpleStorage.sol"); 2 | 3 | contract("SimpleStorage", accounts => { 4 | it("...should store the value 89.", async () => { 5 | const simpleStorageInstance = await SimpleStorage.deployed(); 6 | 7 | // Set value of 89 8 | await simpleStorageInstance.set(89, { from: accounts[0] }); 9 | 10 | // Get stored value 11 | const storedData = await simpleStorageInstance.get.call(); 12 | 13 | assert.equal(storedData, 89, "The value 89 was not stored."); 14 | }); 15 | }); 16 | -------------------------------------------------------------------------------- /server/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "server", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "cors": "^2.8.5", 7 | "express": "^4.17.1", 8 | "express-fileupload": "^1.1.9", 9 | "glob": "^7.1.6", 10 | "web3": "1.2.2" 11 | }, 12 | "scripts": { 13 | "start": "nodemon server.js" 14 | }, 15 | "eslintConfig": { 16 | "extends": "react-app" 17 | }, 18 | "env": { 19 | "es6": true 20 | }, 21 | "devDependencies": { 22 | "babel-eslint": "^10.0.3", 23 | "eslint": "^6.6.0", 24 | "nodemon": "^2.0.1" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /contracts/Migrations.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.5.0; 2 | 3 | contract Migrations { 4 | address public owner; 5 | uint public last_completed_migration; 6 | 7 | modifier restricted() { 8 | if (msg.sender == owner) _; 9 | } 10 | 11 | constructor() public { 12 | owner = msg.sender; 13 | } 14 | 15 | function setCompleted(uint completed) public restricted { 16 | last_completed_migration = completed; 17 | } 18 | 19 | function upgrade(address new_address) public restricted { 20 | Migrations upgraded = Migrations(new_address); 21 | upgraded.setCompleted(last_completed_migration); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /client/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "HealthChain Web App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /client/src/components/DoctorsList.jsx: -------------------------------------------------------------------------------- 1 | import React from "react" 2 | import DoctorsAccessButton from './DoctorsAccessButton' 3 | 4 | const DoctorsList = ({ doctors, contract, accounts, accountId }) => { 5 | return ( 6 |
7 | {doctors && doctors.length && 8 | doctors.map((doctor, index) => { 9 | return
10 |
{doctor.name}
11 |
{accounts[doctor.account]}
12 |
13 | 18 | 19 |
20 |
21 | })} 22 |
23 | ) 24 | } 25 | 26 | export default DoctorsList; -------------------------------------------------------------------------------- /client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "client", 3 | "version": "0.1.0", 4 | "private": true, 5 | "dependencies": { 6 | "bootstrap": "^4.3.1", 7 | "downloadjs": "^1.4.7", 8 | "open-iconic": "^1.1.1", 9 | "react": "16.11.0", 10 | "react-dom": "16.11.0", 11 | "react-router": "^5.1.2", 12 | "react-scripts": "3.2.0", 13 | "web3": "1.2.2" 14 | }, 15 | "scripts": { 16 | "start": "react-scripts start", 17 | "build": "react-scripts build", 18 | "test": "react-scripts test", 19 | "eject": "react-scripts eject" 20 | }, 21 | "eslintConfig": { 22 | "extends": "react-app" 23 | }, 24 | "browserslist": { 25 | "production": [ 26 | ">0.2%", 27 | "not dead", 28 | "not op_mini all" 29 | ], 30 | "development": [ 31 | "last 1 chrome version", 32 | "last 1 firefox version", 33 | "last 1 safari version" 34 | ] 35 | }, 36 | "devDependencies": { 37 | "babel-eslint": "^10.0.3", 38 | "eslint": "^6.6.0", 39 | "eslint-plugin-react": "^7.16.0" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /client/src/components/PatientsOverview.jsx: -------------------------------------------------------------------------------- 1 | import React from "react" 2 | import PatientMedicalRecordsList from './PatientMedicalRecordsList' 3 | 4 | const createPatientList = (patient, doctorsAddress) => { 5 | return ( 6 |
7 |

{patient.address}

8 | 14 | 15 |
16 | ) 17 | } 18 | 19 | const PatientsOverview = ({ patients, doctorsAddress }) => { 20 | console.log(patients) 21 | console.log(patients[0]) 22 | return ( 23 |
24 | {patients && patients.map((patient, index) => { 25 | console.log(patient) 26 | if (patient.address === '0x0000000000000000000000000000000000000000' || 27 | patient.address === doctorsAddress) return '' 28 | return createPatientList(patient, doctorsAddress) 29 | })} 30 |
31 | ) 32 | } 33 | 34 | export default PatientsOverview; -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Marco 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /client/src/components/DoctorView.jsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useRef } from "react" 2 | import ReactDOM from 'react-dom' 3 | import PatientsOverview from "./PatientsOverview" 4 | 5 | const DoctorView = ({ contract, accounts, accountId }) => { 6 | const doctorViewRef = useRef() 7 | useEffect(() => { 8 | const patients = [] 9 | const buildPatientsOverview = async () => { 10 | const doctorsPermissions = await contract.methods.getDoctorsPermissions(accounts[accountId]).call({ from: accounts[accountId], gas: 100000 }) 11 | const seenAddresses = [] 12 | doctorsPermissions.map(async (address, _) => { 13 | if (!seenAddresses.includes(address)) { 14 | seenAddresses.push(address) 15 | const documents = await contract.methods.getDocuments(address).call({ from: accounts[accountId], gas: 100000 }) 16 | patients.push({address: address, documents: documents}) 17 | } 18 | }) 19 | } 20 | buildPatientsOverview() 21 | setTimeout(() => { 22 | ReactDOM.render( 23 | , 24 | doctorViewRef.current 25 | ) 26 | }, 500 27 | ) 28 | /* eslint-disable-next-line */ 29 | }, []) 30 | return ( 31 |
32 | ) 33 | } 34 | 35 | export default DoctorView; -------------------------------------------------------------------------------- /client/src/getWeb3.js: -------------------------------------------------------------------------------- 1 | import Web3 from "web3"; 2 | 3 | const getWeb3 = () => 4 | new Promise((resolve, reject) => { 5 | // Wait for loading completion to avoid race conditions with web3 injection timing. 6 | window.addEventListener("load", async () => { 7 | // Modern dapp browsers... 8 | if (window.ethereum) { 9 | const web3 = new Web3(window.ethereum); 10 | try { 11 | // Request account access if needed 12 | await window.ethereum.enable(); 13 | // Acccounts now exposed 14 | console.log("web3 window.ethereum."); 15 | resolve(web3); 16 | } catch (error) { 17 | reject(error); 18 | } 19 | } 20 | // Legacy dapp browsers... 21 | else if (window.web3) { 22 | // Use Mist/MetaMask's provider. 23 | const web3 = window.web3; 24 | console.log("Injected web3 detected."); 25 | resolve(web3); 26 | } 27 | // Fallback to localhost; use dev console port by default... 28 | else { 29 | const provider = new Web3.providers.HttpProvider( 30 | "http://127.0.0.1:7545" 31 | ); 32 | const web3 = new Web3(provider); 33 | console.log("No web3 instance injected, using Local web3."); 34 | resolve(web3); 35 | } 36 | }); 37 | }); 38 | 39 | export default getWeb3; 40 | -------------------------------------------------------------------------------- /client/src/components/DoctorsAccessButton.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from "react" 2 | 3 | const giveAccessToDoctor = async (doctorAddress, contract, accounts, accountId) => { 4 | await contract.methods.giveAccessToDoctor(doctorAddress).send({ from: accounts[accountId], gas: 100000 }) 5 | const permissions = await contract.methods.getDoctorsPermissions(doctorAddress).call({ from: accounts[accountId], gas: 100000 }) 6 | console.log(permissions) 7 | } 8 | 9 | const revokeAccessFromDoctor = async (doctorAddress, contract, accounts, accountId) => { 10 | const doctorsPermissions = await contract.methods.getDoctorsPermissions(doctorAddress).call({ from: accounts[accountId], gas: 100000 }) 11 | doctorsPermissions.map(async (address, index) => { 12 | if (address === accounts[accountId]) { 13 | await contract.methods.revokeAccessFromDoctor(doctorAddress, index).send({ from: accounts[accountId], gas: 100000 }) 14 | } 15 | }) 16 | } 17 | 18 | const DoctorsAccessButton = ({ doctor, contract, accounts, accountId }) => { 19 | const [hasAccess, setHasAccess] = useState(doctor.hasAccess) 20 | return ( 21 |
22 | {hasAccess && 23 | 30 | } 31 | {!hasAccess && 32 | 39 | } 40 |
41 | ) 42 | } 43 | 44 | export default DoctorsAccessButton; -------------------------------------------------------------------------------- /client/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | HealthChain Web App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /contracts/Healthchain.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.5.0; 2 | /* ABIEncoderV2 is needed to return an array from a function. */ 3 | pragma experimental ABIEncoderV2; 4 | 5 | contract Healthchain { 6 | 7 | /* Every user has a list of documents. */ 8 | mapping (address => string[]) public documents; 9 | 10 | /** 11 | * Add a medical record. 12 | * Returns the index of the medical record. 13 | */ 14 | function addDocument(string memory documentHash) public returns (uint) { 15 | address from = msg.sender; 16 | // push returns the array length 17 | return documents[from].push(documentHash) - 1; 18 | } 19 | 20 | /** 21 | * Get all medical records of a user. 22 | */ 23 | function getDocuments(address user) public view returns (string[] memory) { 24 | return documents[user]; 25 | } 26 | 27 | /** 28 | * A user can specify, which doctors are allowed to view their medical records. 29 | * Access is granted, when the user adds his address to a doctors list of patients. 30 | * As soon as the user address is removed from the list, access for the doctor is revoked. 31 | * 32 | * mapping: doctorsAddress -> patientsAddresses 33 | */ 34 | mapping (address => address[]) public doctorsPermissions; 35 | 36 | /** 37 | * Allow a doctor to view all your documents. 38 | */ 39 | function giveAccessToDoctor(address doctor) public { 40 | doctorsPermissions[doctor].push(msg.sender); 41 | } 42 | 43 | /** 44 | * Revoke a doctors access to your documents. 45 | */ 46 | function revokeAccessFromDoctor(address doctor, uint index) public { 47 | require(doctorsPermissions[doctor][index] == msg.sender, 'You can only revoke access to your own documents.'); 48 | delete doctorsPermissions[doctor][index]; 49 | } 50 | 51 | /** 52 | * Returns all the patients addresses that gave the doctor access. 53 | */ 54 | function getDoctorsPermissions(address doctor) public view returns (address[] memory) { 55 | return doctorsPermissions[doctor]; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Healthchain 2 | 3 | Store your medical records in a blockchain and give doctors permissions when they need it :hospital: 4 | 5 | ### :warning: :warning: :warning: 6 | This projects is a proof of concept and by no means ready to use in real world use cases. Deploying the smart contract on the real ethereum network might result in high costs! 7 | 8 | ## About 9 | 10 | ### Patient's view 11 | 12 | A patient can log in to the web-app and upload his medical records. 13 | A list of all uploaded documents is displayed. The documents can be downloaded or deleted. After a medical record document is uploaded, the patient can give a doctor access to his documents. As soon as the Doctor doesn't need access anymore, the permissions can be revoked. 14 | 15 | ![](images/patient_view.jpg) 16 | 17 | ### Doctor's view 18 | 19 | A doctor sees all documents that he has access to. Document can be downloaded to view them. 20 | 21 | ![](images/doctor_view.jpg) 22 | 23 | ## Setup development environment 24 | 25 | 1. Install Ganche from the [official webpage](https://www.trufflesuite.com/ganache) or the latest [release on github](https://github.com/trufflesuite/ganache/releases). 26 | 2. run `npm install truffle -g` to install truffle globally 27 | 3. [Windows] If you don't have Visual Studio installed, run `npm install --global --production windows-build-tools` 28 | 29 | ## Building the smart contract 30 | 31 | 1. Start Ganache and create a new workspace (quickstart). Make sure the RPC server is set to 127.0.0.1:7545. 32 | 2. in the root of this repository, run: 33 | ```bash 34 | truffle compile 35 | truffle migrate 36 | ``` 37 | 3. Copy the smart contract to the server: 38 | ``` 39 | copy-contracts-to-server.ps1 40 | ``` 41 | By default the smart contract is deployed to the client. Truffle can't deploy to multiple directories. 42 | 43 | ## Client 44 | 45 | A website for patients and doctors to store, view and manage medical records. 46 | 47 | Start the react app: 48 | ``` 49 | cd client 50 | npm start 51 | ``` 52 | 53 | ## Server 54 | Files are uploaded to the server. The server can access the blockchain to check if a user is allowed to download the requested file. 55 | 56 | Start the nodejs server: 57 | ``` 58 | cd server 59 | npm start 60 | ``` 61 | 62 | ## testimonials 63 | 64 | This project is based on the react truffle box: https://www.trufflesuite.com/boxes/react 65 | -------------------------------------------------------------------------------- /client/src/components/PatientMedicalRecordsList.jsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from "react" 2 | import download from 'downloadjs' 3 | 4 | const getFileNameForHash = async (hash) => { 5 | const response = await fetch('http://localhost:3001/GetFileName/' + hash) 6 | const data = await response.json().catch(err => console.log(err)) 7 | if (!data || !data.name) return 'Upload failed. Try again later.' 8 | console.log(data.name) 9 | return data.name 10 | } 11 | 12 | const downloadMedicalRecord = async (medicalRecord, userAddress, patientAddress) => { 13 | const name = await getFileNameForHash(medicalRecord) 14 | const x = new XMLHttpRequest(); 15 | const url = "http://localhost:3001/DownloadMedicalEvidence/" + 16 | userAddress + "/" + 17 | patientAddress + "/" + 18 | medicalRecord 19 | x.open("GET", url, true); 20 | x.responseType = "blob"; 21 | x.onload = function (e) { download(e.target.response, name, "image/png"); }; 22 | x.send(); 23 | } 24 | 25 | const PatientMedicalRecordsList = ({ items: medicalRecords, userAddress, patientAddress, isDoctor = false }) => { 26 | 27 | useEffect(() => { 28 | const getNames = async (id) => { 29 | const nameElement = document.getElementById(id) 30 | const name = await getFileNameForHash(id) 31 | console.log(name) 32 | nameElement.innerHTML = name.replace(id + '_', '') 33 | } 34 | medicalRecords.map((medicalRecord, index) => getNames(medicalRecord)) 35 | /* eslint-disable-next-line */ 36 | }) 37 | return ( 38 |
39 | {!(medicalRecords && medicalRecords.length) && 40 | 'No medical records uploaded yet.'} 41 | {medicalRecords && 42 | medicalRecords.map((medicalRecord, index) => { 43 | console.log(medicalRecord) 44 | return
45 |
46 |
{medicalRecord}
47 |
48 | 53 |
54 | {!isDoctor && 55 |
56 | 57 |
58 | } 59 |
60 | })} 61 |
62 | ) 63 | } 64 | 65 | export default PatientMedicalRecordsList; -------------------------------------------------------------------------------- /client/README.md: -------------------------------------------------------------------------------- 1 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 2 | 3 | ## Available Scripts 4 | 5 | In the project directory, you can run: 6 | 7 | ### `yarn start` 8 | 9 | Runs the app in the development mode.
10 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 11 | 12 | The page will reload if you make edits.
13 | You will also see any lint errors in the console. 14 | 15 | ### `yarn test` 16 | 17 | Launches the test runner in the interactive watch mode.
18 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 19 | 20 | ### `yarn build` 21 | 22 | Builds the app for production to the `build` folder.
23 | It correctly bundles React in production mode and optimizes the build for the best performance. 24 | 25 | The build is minified and the filenames include the hashes.
26 | Your app is ready to be deployed! 27 | 28 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 29 | 30 | ### `yarn eject` 31 | 32 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 33 | 34 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 35 | 36 | Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 37 | 38 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 39 | 40 | ## Learn More 41 | 42 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 43 | 44 | To learn React, check out the [React documentation](https://reactjs.org/). 45 | 46 | ### Code Splitting 47 | 48 | This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting 49 | 50 | ### Analyzing the Bundle Size 51 | 52 | This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size 53 | 54 | ### Making a Progressive Web App 55 | 56 | This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app 57 | 58 | ### Advanced Configuration 59 | 60 | This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration 61 | 62 | ### Deployment 63 | 64 | This section has moved here: https://facebook.github.io/create-react-app/docs/deployment 65 | 66 | ### `yarn build` fails to minify 67 | 68 | This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify 69 | -------------------------------------------------------------------------------- /client/src/components/LogInOrRegister.jsx: -------------------------------------------------------------------------------- 1 | import React from "react" 2 | import { doctors, patients } from '../helpers/users' 3 | 4 | const LogInOrRegister = () => { 5 | 6 | const logInRef = React.useRef() 7 | const logInEmailRef = React.useRef() 8 | 9 | const dispatchLogInSuccessEvent = () => { 10 | document.dispatchEvent(new CustomEvent('logInSuccessful')) 11 | } 12 | 13 | // fake log in mechanism 14 | const logIn = (e) => { 15 | const email = logInEmailRef.current.value 16 | console.log('try log in as: ' + email) 17 | if (email.includes('doctor')) { 18 | localStorage.setItem('user', doctors[0].name) 19 | localStorage.setItem('isDoctor', true) 20 | localStorage.setItem('accountId', doctors[0].account) 21 | dispatchLogInSuccessEvent() 22 | } else { 23 | localStorage.setItem('user', patients[0].name) 24 | localStorage.setItem('isDoctor', false) 25 | localStorage.setItem('accountId', patients[0].account) 26 | dispatchLogInSuccessEvent() 27 | } 28 | } 29 | React.useEffect( 30 | () => { 31 | const logInElement = logInRef.current 32 | logInElement.addEventListener('click', logIn) 33 | return () => { 34 | logInElement.removeEventListener('click', logIn) 35 | } 36 | /* eslint-disable-next-line */ 37 | }, [] 38 | ) 39 | 40 | return ( 41 |
42 |

Log in

43 |

For existing users.

44 |
45 |
46 | Email address: 47 |
48 | 49 |
50 |
51 |
52 | Password: 53 |
54 | 55 |
56 | 57 | 58 |
59 | 60 |

Register

61 |

As a new user.

62 |
63 |
64 | First Name: 65 |
66 | 67 |
68 | Last Name: 69 |
70 | 71 |
72 |
73 |
74 | Email address: 75 |
76 | 77 |
78 |
79 |
80 | Password: 81 |
82 | 83 |
84 | We'll never share your personal data with anyone else. 85 | 86 |
87 | ) 88 | } 89 | 90 | export default LogInOrRegister; -------------------------------------------------------------------------------- /server/server.js: -------------------------------------------------------------------------------- 1 | const express = require('express') 2 | const app = express() 3 | const port = 3001 || process.env.PORT 4 | const Web3 = require('web3') 5 | const cors = require('cors') 6 | const fileUpload = require('express-fileupload') 7 | const HealthchainContract = require("./contracts/Healthchain.json") 8 | const glob = require('glob') 9 | 10 | const web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:7545")) 11 | 12 | let healthchain_contract = null 13 | 14 | // configure cors 15 | var whitelist = ['http://localhost:3000', 'http://127.0.0.1:3000'] 16 | var corsOptions = { 17 | origin: function (origin, callback) { 18 | if (whitelist.indexOf(origin) !== -1) { 19 | callback(null, true) 20 | } else { 21 | callback(new Error('Not allowed by CORS')) 22 | } 23 | } 24 | } 25 | app.use(cors(corsOptions)) 26 | 27 | // configure file upload 28 | app.use(fileUpload({ 29 | limits: { fileSize: 10 * 1024 * 1024 }, 30 | })); 31 | 32 | // GET server welcome message 33 | app.get('/', (req, res) => { 34 | res.send('hello world!') 35 | }); 36 | 37 | // POST a new medical record 38 | app.post('/UploadMedicalEvidence/', (req, res) => { 39 | if (!req.files || Object.keys(req.files).length === 0) { 40 | return res.status(400).send('No files were uploaded.') 41 | } 42 | 43 | // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file 44 | let medicalRecord = req.files.medicalRecord; 45 | console.log(medicalRecord.md5) 46 | // Use the mv() method to place the file somewhere on your server 47 | medicalRecord.mv('./medical-records/' + medicalRecord.md5 + '_' + medicalRecord.name, function (err) { 48 | if (err) return res.status(500).send(err); 49 | }); 50 | res.send({ 'hash': medicalRecord.md5 }); 51 | }) 52 | 53 | // GET the name of a file 54 | app.get('/GetFileName/:hash', (req, res) => { 55 | const hash = req.params.hash 56 | glob('./medical-records/' + hash + '*', (err, files) => { 57 | if (err) return res.status(404).send('no file found for hash ' + hash) 58 | 59 | if (!files[0]) res.status(404).send('no file found for hash ' + hash) 60 | res.send({ name: files[0].split('./medical-records/')[1] }); 61 | }) 62 | }) 63 | 64 | // GET a document 65 | app.get('/DownloadMedicalEvidence/:user/:patient/:document', async (req, res) => { 66 | const documentHash = req.params.document 67 | const userAddress = req.params.user 68 | const patientAddress = req.params.patient 69 | 70 | try { 71 | const doctorPermissions = await healthchain_contract.methods.getDoctorsPermissions(userAddress).call(); 72 | console.log(doctorPermissions) 73 | if (!doctorPermissions.includes(patientAddress) && userAddress != patientAddress) return res.send('Access denied!') 74 | 75 | const documents = await healthchain_contract.methods.getDocuments(patientAddress).call(); 76 | console.log(documents) 77 | if (!documents.includes(documentHash)) return res.send('This document doesn\'t belong to the specified patient!') 78 | } catch (err) { 79 | return res.send('Access denied!') 80 | } 81 | 82 | console.log('trying to download ' + documentHash) 83 | glob('./medical-records/' + documentHash + '*', (err, files) => { 84 | if (err) return res.status(404).send('no file found for hash ' + documentHash) 85 | 86 | res.download(files[0]); 87 | }) 88 | }) 89 | 90 | app.listen(port, async () => { 91 | // Get the contract instance. 92 | const networkId = await web3.eth.net.getId(); 93 | const deployedNetwork = HealthchainContract.networks[networkId]; 94 | console.log('deployment network: ' + deployedNetwork) 95 | healthchain_contract = new web3.eth.Contract( 96 | HealthchainContract.abi, 97 | deployedNetwork && deployedNetwork.address, 98 | ); 99 | console.log("Express Listening at http://localhost:" + port) 100 | }) -------------------------------------------------------------------------------- /client/src/App.jsx: -------------------------------------------------------------------------------- 1 | import React, { Component } from "react"; 2 | import PatientView from './components/PatientView' 3 | import DoctorView from './components/DoctorView' 4 | import HealthchainContract from "./contracts/Healthchain.json"; 5 | import getWeb3 from "./getWeb3"; 6 | import "./App.css"; 7 | import 'open-iconic/font/css/open-iconic-bootstrap.css' 8 | import 'bootstrap/dist/css/bootstrap.css'; 9 | import LogInOrRegister from "./components/LogInOrRegister"; 10 | import { doctors, patients } from './helpers/users' 11 | 12 | class App extends Component { 13 | state = { 14 | web3: null, 15 | accounts: null, 16 | contract: null, 17 | user: null, 18 | isDoctor: false, 19 | accountId: null 20 | }; 21 | 22 | componentDidMount = async () => { 23 | try { 24 | // Get network provider and web3 instance. 25 | const web3 = await getWeb3(); 26 | 27 | // Use web3 to get the user's accounts. 28 | const accounts = await web3.eth.getAccounts(); 29 | 30 | // Get the contract instance. 31 | const networkId = await web3.eth.net.getId(); 32 | const deployedNetwork = HealthchainContract.networks[networkId]; 33 | const instance = new web3.eth.Contract( 34 | HealthchainContract.abi, 35 | deployedNetwork && deployedNetwork.address, 36 | ); 37 | 38 | // Set web3, accounts, and contract to the state, and then proceed with an 39 | // example of interacting with the contract's methods. 40 | this.setState({ web3, accounts, contract: instance }); 41 | } catch (error) { 42 | // Catch any errors for any of the above operations. 43 | alert( 44 | `Failed to load web3, accounts, or contract. Check console for details.`, 45 | ); 46 | console.error(error); 47 | } 48 | 49 | const updateLogInFromLocalStorage = () => { 50 | if (localStorage.getItem('user') === 'null') return 51 | const user = localStorage.getItem('user') 52 | const isDoctor = localStorage.getItem('isDoctor') === 'true' 53 | const accountId = parseInt(localStorage.getItem('accountId')) 54 | this.setState({ user, isDoctor, accountId }) 55 | } 56 | document.addEventListener('logInSuccessful', updateLogInFromLocalStorage, false) 57 | updateLogInFromLocalStorage() 58 | }; 59 | 60 | render() { 61 | 62 | if (!this.state.web3) { 63 | return
Loading Web3, accounts, and contract...
; 64 | } 65 | 66 | const changeLogIn = (user, isDoctor, accountId) => { 67 | localStorage.setItem('user', user) 68 | localStorage.setItem('isDoctor', isDoctor) 69 | localStorage.setItem('accountId', accountId) 70 | this.setState({ user, isDoctor, accountId }) 71 | } 72 | 73 | return ( 74 |
75 | 76 | {/* DEBUG STUFF */} 77 | 80 | 81 | 84 | 85 | 88 | 89 |
90 | 91 |
92 |

93 | 94 | HEALTHCHAIN 95 |

96 | {this.state.user && 97 |

Logged in as {this.state.user}

98 | } 99 |
100 | 101 |
102 | {!this.state.user && !this.state.isDoctor && 103 | 104 | } 105 | {this.state.user && !this.state.isDoctor && 106 | 107 | } 108 | {this.state.user && this.state.isDoctor && 109 | 110 | } 111 |
112 | 113 |
114 |
115 | ); 116 | } 117 | } 118 | 119 | export default App; 120 | -------------------------------------------------------------------------------- /client/src/components/PatientView.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect, useRef } from "react" 2 | import ReactDOM from 'react-dom' 3 | import DoctorsList from "./DoctorsList" 4 | import { doctors } from '../helpers/users' 5 | import PatientMedicalRecordsList from "./PatientMedicalRecordsList" 6 | 7 | /** 8 | * Upload a document to the server and add the document hash to the smart contract. 9 | */ 10 | const uploadMedicalRecord = async (contract, accounts, accountId, medicalRecordInput) => { 11 | const file = medicalRecordInput.files[0] 12 | console.log(file) 13 | const formData = new FormData() 14 | formData.append(medicalRecordInput.id, file) 15 | const response = await fetch('http://localhost:3001/UploadMedicalEvidence/', { 16 | method: 'POST', 17 | headers: { 18 | }, 19 | body: formData 20 | }) 21 | const data = await response.json().catch(err => console.log(err)) 22 | try { 23 | if (!data || !data.hash) return 'Upload failed. Try again later.' 24 | console.log(data.hash) // Handle the success response object 25 | 26 | // use call to get the value from this transaction, no changes made yet!!! 27 | const documentIndex = await contract.methods.addDocument(data.hash).call({ from: accounts[accountId] }); 28 | // actual changes here!!! 29 | await contract.methods.addDocument(data.hash).send({ from: accounts[accountId] }); 30 | // Get the value from the contract to prove it worked. 31 | const myDocuments = await contract.methods.getDocuments(accounts[accountId]).call({ from: accounts[accountId], gas: 100000 }); 32 | console.log(myDocuments) 33 | const documentHash = myDocuments[documentIndex]; 34 | console.log("response from getDocuments", documentHash) 35 | return 'Successfully uploaded medical record \'' + file.name + '\' and added it to the blockchain as \'' + documentHash + '\'' 36 | } 37 | catch (error) { 38 | console.log(error) // Handle the error response object 39 | return 'Please select a file to upload.' 40 | }; 41 | } 42 | 43 | const PatientView = ({ contract, accounts, accountId }) => { 44 | const [uploadResponse, setUploadResponse] = useState() 45 | 46 | const medicalRecordsListRef = useRef() 47 | const doctorsListRef = useRef() 48 | 49 | useEffect(() => { 50 | async function getDocuments() { 51 | const documents = await contract.methods.getDocuments(accounts[accountId]).call({ from: accounts[accountId], gas: 100000 }) 52 | ReactDOM.render( 53 | , 57 | medicalRecordsListRef.current 58 | ) 59 | } 60 | getDocuments() 61 | /* eslint-disable-next-line */ 62 | }, [uploadResponse]) 63 | 64 | useEffect(() => { 65 | const getDoctors = async () => { 66 | await doctors.map(async (doctor, index) => { 67 | const permissions = await contract.methods.getDoctorsPermissions(accounts[doctor.account]).call({ from: accounts[accountId], gas: 100000 }) 68 | doctors[index].hasAccess = permissions.includes(accounts[accountId]) 69 | }) 70 | setTimeout(() => { 71 | console.log(doctors[0].hasAccess) 72 | ReactDOM.render( 73 | 77 | , 78 | doctorsListRef.current 79 | ) 80 | }, 300); 81 | } 82 | getDoctors() 83 | /* eslint-disable-next-line */ 84 | }, []) 85 | 86 | return (
87 |

Upload a medical record

88 |
89 | 90 |
91 | 95 | {uploadResponse && 96 |
{uploadResponse}
97 | } 98 | 99 |
100 |

Manage permissions

101 |
If you give access to a doctor, the doctor is able to view all your medical records.
102 |
103 | 104 |

Manage your medical records

105 |
View or delete your medical records.
106 |
107 |
108 | ) 109 | } 110 | 111 | export default PatientView; -------------------------------------------------------------------------------- /client/src/serviceWorker.js: -------------------------------------------------------------------------------- 1 | // This optional code is used to register a service worker. 2 | // register() is not called by default. 3 | 4 | // This lets the app load faster on subsequent visits in production, and gives 5 | // it offline capabilities. However, it also means that developers (and users) 6 | // will only see deployed updates on subsequent visits to a page, after all the 7 | // existing tabs open on the page have been closed, since previously cached 8 | // resources are updated in the background. 9 | 10 | // To learn more about the benefits of this model and instructions on how to 11 | // opt-in, read https://bit.ly/CRA-PWA 12 | 13 | const isLocalhost = Boolean( 14 | window.location.hostname === 'localhost' || 15 | // [::1] is the IPv6 localhost address. 16 | window.location.hostname === '[::1]' || 17 | // 127.0.0.1/8 is considered localhost for IPv4. 18 | window.location.hostname.match( 19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ 20 | ) 21 | ); 22 | 23 | export function register(config) { 24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { 25 | // The URL constructor is available in all browsers that support SW. 26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); 27 | if (publicUrl.origin !== window.location.origin) { 28 | // Our service worker won't work if PUBLIC_URL is on a different origin 29 | // from what our page is served on. This might happen if a CDN is used to 30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374 31 | return; 32 | } 33 | 34 | window.addEventListener('load', () => { 35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; 36 | 37 | if (isLocalhost) { 38 | // This is running on localhost. Let's check if a service worker still exists or not. 39 | checkValidServiceWorker(swUrl, config); 40 | 41 | // Add some additional logging to localhost, pointing developers to the 42 | // service worker/PWA documentation. 43 | navigator.serviceWorker.ready.then(() => { 44 | console.log( 45 | 'This web app is being served cache-first by a service ' + 46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA' 47 | ); 48 | }); 49 | } else { 50 | // Is not localhost. Just register service worker 51 | registerValidSW(swUrl, config); 52 | } 53 | }); 54 | } 55 | } 56 | 57 | function registerValidSW(swUrl, config) { 58 | navigator.serviceWorker 59 | .register(swUrl) 60 | .then(registration => { 61 | registration.onupdatefound = () => { 62 | const installingWorker = registration.installing; 63 | if (installingWorker == null) { 64 | return; 65 | } 66 | installingWorker.onstatechange = () => { 67 | if (installingWorker.state === 'installed') { 68 | if (navigator.serviceWorker.controller) { 69 | // At this point, the updated precached content has been fetched, 70 | // but the previous service worker will still serve the older 71 | // content until all client tabs are closed. 72 | console.log( 73 | 'New content is available and will be used when all ' + 74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' 75 | ); 76 | 77 | // Execute callback 78 | if (config && config.onUpdate) { 79 | config.onUpdate(registration); 80 | } 81 | } else { 82 | // At this point, everything has been precached. 83 | // It's the perfect time to display a 84 | // "Content is cached for offline use." message. 85 | console.log('Content is cached for offline use.'); 86 | 87 | // Execute callback 88 | if (config && config.onSuccess) { 89 | config.onSuccess(registration); 90 | } 91 | } 92 | } 93 | }; 94 | }; 95 | }) 96 | .catch(error => { 97 | console.error('Error during service worker registration:', error); 98 | }); 99 | } 100 | 101 | function checkValidServiceWorker(swUrl, config) { 102 | // Check if the service worker can be found. If it can't reload the page. 103 | fetch(swUrl) 104 | .then(response => { 105 | // Ensure service worker exists, and that we really are getting a JS file. 106 | const contentType = response.headers.get('content-type'); 107 | if ( 108 | response.status === 404 || 109 | (contentType != null && contentType.indexOf('javascript') === -1) 110 | ) { 111 | // No service worker found. Probably a different app. Reload the page. 112 | navigator.serviceWorker.ready.then(registration => { 113 | registration.unregister().then(() => { 114 | window.location.reload(); 115 | }); 116 | }); 117 | } else { 118 | // Service worker found. Proceed as normal. 119 | registerValidSW(swUrl, config); 120 | } 121 | }) 122 | .catch(() => { 123 | console.log( 124 | 'No internet connection found. App is running in offline mode.' 125 | ); 126 | }); 127 | } 128 | 129 | export function unregister() { 130 | if ('serviceWorker' in navigator) { 131 | navigator.serviceWorker.ready.then(registration => { 132 | registration.unregister(); 133 | }); 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /client/src/logo.svg: -------------------------------------------------------------------------------- 1 | --------------------------------------------------------------------------------