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 | 
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 | 
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 |
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
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 |
--------------------------------------------------------------------------------