Blockchain In PKI As An Access Management API: Petmeddata

Edward Burton
11 min readAug 8, 2018
Dogs on a blockchain? Now that is a good idea!!
  • Why Petmeddata need Blockchain
  • How we use Blockchain?
  • Technical specs
  • Show me the code…
  • Conclusion
  • Landing page for the project: https://petmeddata.com/

PetmedData and why they need Blockchain

Wherever you are on the Blockchain spectrum a common (and legitimate) argument in the sector is that “no-one can tell me a successful public project that uses Blockchain”. Proof of concept development and ideas are widespread, as well as a proliferation of private behind-closed-doors transactional Blockchain systems using smart contracts for financial transactions (which obfuscates much of the work done in the sector). But so far few of these projects have matured to the battle-hardened state where they are happy to publicly stick the Blockchain flag in the ground.

After several years of working with Blockchain technology (and 19 Blockchain patents pending / granted) we’ve a fair bit of experience of the problems of applying Blockchain to production environments. We are currently working on (aiming for a September launch of the pre-beta) an interesting Blockchain project that we are allowed to talk openly about and that will be open to the public (in the form of a mobile web application, no DAPPs here…) The project is Petmeddata, and it is a Blockchain platform that will allow pet owners to upload and manage their pets’ data, specifically their medical records.

The owner can upload previous medical records, notes and photos and videos to their pet’s profile. In most cases the owner then grants a veterinary health care professional access to their pet’s profile. Having done this the vet or other professional can upload medical data to the pet’s profile. Access can be granted by sending a symmetric key to deencrypt the record via Blockchain using the Petmeddata application or by having a custom integration to the Blockchain from a Patient Management System (PMS). The first PMSes integrated with Petmeddata will be Provet Net and Provet Cloud (more information on www.provet.info).

Why does a pet healthcare application need a Blockchain you ask? Well actually, for some very interesting and valid reasons.

  1. Security: The first requirement of the project is that the owners of the private Blockchain infrastructure should have no vision of the medical data flowing through their systems and that it be fully GDPR compliant; in fact we have used Blockchain alongside symmetric and asymmetric encryption to create a PKI which guarantees that only the pet owner and their specifically designated recipients (those who have been sent the symmetric key) will be able to access the data (we will explain how later). Using the trustlessness of Blockchain we have an immutable rock-solid PKI which verifies, encrypts and decrypts user data and is never exposed even to the Blockchain sys-admins.
  2. Co-operation: The owners of the Blockchain infrastructure are big players in the PMS (Patient Management System) space, by using Blockchain as a PKI in a decentralized peer-to-peer system they open up business opportunities to ‘cooperate’ rather than ‘compete’ with other PMSes. This is a really interesting aspect, a traditional model would be a race to market by each PMS operator and a multitude of smaller systems in competition. By using Blockchain, their competitors can white-label the underlying Blockchain and build their applications on top of a more mature database / infrastructure. As no-one “owns” the data (except the pet owner), competitors can legitimately build their businesses on top of a shared data source.
  3. Transparency: The Blockchain doesn’t lie. By using Blockchain as the foundation of the data protocol of the project, every API built on the Blockchain is policing and has insight into the data flow of the medical records. The more the Blockchain scales, the more secure it becomes as competing API’s built on the same infrastructure act to keep each other in check. The underlying system belongs to everybody. This is the United Nations model whereby every actor has motivation to contribute towards the well-being of the system, police nodes help make sure there are no malicious actors (and as all relevant actions are published to the Blockchain, it is difficult to hide malicious actions).
  4. Trust: Building this system without a Blockchain would be possible. But you would have to trust the architects to do as they have said they have done. “We can’t see your data, honest!”. Google / Amazon / Facebook will all have internal firewalls to stop the interns from accessing your private data flowing through their systems. But do you trust them? The Blockchain system has end to end encryption (with the secure keys saved locally on your mobile device) and this flow is validated and utilized by competing actors. You may, or you may not trust Google / Amazon / Facebook to behave responsibly and never ‘peek’ at your private data, but you can bet your house that if they were sharing the same infrastructure they would make sure that the others are behaving responsibly…

How we use Blockchain

Sounds complicated right? It kind of is, but as Einstein said:

Albert Einstein would have loved Blockchain

If you can’t explain it simply, you don’t understand it well enough.

There are still many ways the Blockchain world is developing, but the fundamental applications are still ripe ground for harvesting. Some key principals of Chainfrog at this stage of the Blockchain evolution are:

  • You probably don’t need smart contracts (unless you are executing some kind of physical asset exchange).
  • If it is data, it should be in a database (not a Blockchain).
  • If it isn’t obvious why you need Blockchain, you don’t need it.

So what are the core applications of our Blockchain, our immutable, trustless distributed ledger? First, the Blockchain cannot lie. This makes it absolutely perfect as a Distributed Certificate Authority for Public Key Infrastructure. Specifically, we use asymmetric cryptography to send symmetric keys. Simple, but a perfect use of Blockchain.

It goes a little something like this:

A. A new user generates a public-private key pair, and publishes the public key to the Blockchain.

B. This user generates a patient profile for the pet, encrypted with a symmetric key.

C. The user now has an encrypted cloud stored pet profile for storing medical records, which are only accessible using private keys available on their local device.

D. The user can now share the symmetric key to allow a recipient to access the pets profile and decrypt their medical records via the Blockchain. They encrypt this key using the recipients public key (published on the Blockchain) .

E. The recipient can now see the pet’s profile and medical records.

F. Both the healthcare professional and pet owner can now view the profile, and publish medical information and data to the patient record.

So, a Blockchain (as shown with Bitcoin) is a great mechanism for psuedo-anonymous data sharing, that is to say the Blockchain acts as the intermediary for users to send transactions through the Blockchain which will maintain a cryptographically secure trustless record of the transactions. Once we’ve got over the big words, what does this mean. In terms of our application:

1. A pet owner

2. Can register with the Blockchain, (mapping their preferred OAuth authorization API to their anonymous public key published on the Blockchain)

3. Can upload data to a NoSql cloud database encrypted with a symmetric key

4. Can securely share this hidden symmetric key with other users of the Blockchain by using asymmetric encryption

5. The recipient of the symmetric key (veterinary or medical professionals) can now access the encrypted data, without ever exposing medical records to sys-admins or malicious actors.

6. The sys-admin, at no point ever has access to the unencrypted data… In fact, only the owner of the medical record and recipient will ever have access to the encrypted data, which lives in any no-sql cloud database (with all the additional security this entails!).

And that… Is our vision of how to use the properties of Blockchain in a scalable infrastructure utilizing all the fundamental advantages of the Blockchain.

Technical specs

How does one go about building such a system? Truth be told, there are many cocktails of technology that could build the infrastructure. We’ve chosen a technology stack that suits our team and fits our principal of ‘keep it simple’. The credits go like this:

Front-end:

Angular 6 PWA — https://angular.io/

Middleware:

Aiohttp (Python API) —https://aiohttp.readthedocs.io/en/stable/web_quickstart.html

Blockchain:

Multichain — https://www.multichain.com/

Database:

Firestore — https://firebase.google.com/docs/firestore/

Authentification:

Firebase — https://firebase.google.com/

The interesting part of the stack is that although we ship a SDK with the Blockchain for third parties to integrate with the system, to extend the Blockchain to new participants we just need to authorize access to a new node, and the actor can then build their own front-end and middleware on top of the same Blockchain PKI. Potentially they could also change the authorization API and the database (as long as there was agreement about database management and they complied with the fundamental security requirements). It all comes down to consensus and policing and as someone who has spent over a decade in web development, it does feel like a step forward from the current monolith structure. The Blockchain controls encryption, access and sharing. the PKI is the lynchpin, and on top of that you can use whichever middleware and front-end you would use in your normal development stack. There is no need for custom wallets and DAPPs with our implementation.

The Aiohttp API works as middleware to interact with the Blockchain, exposing endpoints for our front-end to interact with the Blockchain. As the Blockchain runs on several nodes, it doesn’t really matter which web application is publishing to the Blockchain, as long as it has been authorized. The API also has admin integrations with the database for standard security protocols, such as ensuring that users can only access records they have permission to access (even if it is all encrypted). So it is essentially a standard API with bonus Blockchain features, such as making sure that all the access controls and permissions are trustless and immutable.

In this structure multiple PMSes could simultaneously publish to the Blockchain on separate nodes, but still be using the same underlying system and structure. The Multichain code (we are big fans) is based on original Bitcoin API and has comprehensive security features (that is to say even a malicious actor would have a hard time doing anything truly ‘evil’ on the system), but the beauty of the Blockchain is that every node and actor would be policing the other.

There are loads of really fun harmonies that just make building a system in this way ‘feel right’. For example, every time a new medical record is published to the Blockchain, the Blockchain API returns a unique transaction ID. This transaction ID can then be used as the ‘document’ ID in the NoSQL database, creating harmony between database querying and having anonymous data storage. The icing on the cake is that by publishing a cryptographic hash of the encrypted document record on the Blockchain (which returns the transaction ID), you now have a permanent verification via Blockchain that the data has not been tampered with, while the encrypted data is anonymously stored in a NoSQL database.

The worst thing that can happen to your data now is that someone ‘deletes’ it from the database (it cannot never be altered without you noticing). Apart from the fact that this is a risk in ‘any’ database and structure, there are standard system administration practices you can implement to mitigate such risks. The PMD system is a marriage between databases and Blockchain in a scalable system infrastructure that just feels right!

Building this system is a pleasure, and our stress-testing suggests that this should be a scaleable application of the advantages of Blockchain.

Show me the code

I know that the Medium community tends to be ‘code-inclined’ so I’ll post some code snippets to give some insight into how the system is put together.

First, we have to open the session with the Python API (and retrieve the permissions and authorization from the Blockchain). They Python API will run all the appropriate checks to ensure that the users has permission (as per the Blockchain).

// Open the session for the user using the generated Keypair and return the session token to Angular.
openSession(uid,keyPair) : Observable<promise> {
return this.http.post(
this.host+'/sessions?user_id='+uid,
keyPair,
{headers : new HttpHeaders().set('Content-Type', 'text/plain'), responseType: 'text'}
);
}

With the verified session we can now use an Angular Service to post medical record to Python backend. The session is being managed by the Python API to run all the appropriate checks.

// Code snippet to post to Python API, the Python API then encrypts and writes the record to the database. The API returns the transaction ID.
createClinicalRecord(patientId, record) : Observable<promise> {
return this.http.post(
this.host+'/patients/'+patientId+'/records?session='+this.sessionKey,
record
);
}

Python API then does some processing to encrypt record and post to Firestore.

async def async def collection_post_put(request):
'''
Encrypt and save a document in Firestore using a specified patient key

session must be passed as a parameter, payload is file to encrypt.
content-type may be anything, it will be recorded in the saved document.
Response payload is the ID of encrypted record (application/json).
'''
status = 200
patient_id = request.match_info['patient_id']
if request.method == 'PUT':
doc_id = request.match_info['doc_id']
else:
doc_id = None
collection = request.match_info['collection']
if 'session' in request.query:
session_key = request.query['session']
else:
status = 400 # Bad request
if collection not in valid_collections:
status = 404 # Not found
if status == 200:
try:
plaintext = await request.content.read()
(aes_key, key_version) = await request.app.key_manager.get_patient_key(session_key,
patient_id)
ciphertext = request.app.key_manager.encrypt_with_symmetric_key(aes_key, plaintext)
ciphertext_b64 = base64.b64encode(ciphertext)
encrypted_object = {'key_version' : key_version,
'content_type' : request.content_type,
'created' : datetime.now(),
'encrypted_record': str(ciphertext_b64, 'utf8')}
# Special processing for clinical records
if collection == 'records':
try:
unencrypted_object = json.loads(str(plaintext, 'utf8'))
encrypted_object['tags'] = unencrypted_object.get('tags', [])
except:
logger.warning('Could not get tags from clinical record')
if doc_id is None:
doc_id = await request.app.fs.create(encrypted_object, 'patients', patient_id,
collection)
status = 201 # Created
else:
await request.app.fs.set(encrypted_object, 'patients', patient_id, collection,
doc_id)
except SessionManagerException as sme:
logger.warning(str(sme))
status = 408 # Request timeout
except KeyManagerException as kme:
logger.warning(str(kme))
status = kme.status or 422 # Unprocessable entity
except Exception as e:
log_exception(e)
status = 401 # Unauthorized
return web.json_response(status=status, data=doc_id)Firestore
In Firestore we simply have encrypted data, inaccessible even to system administrators

Conclusion

In Petmeddata we have a genuine Blockchain use case and a really fun and relevant system to build. We have stuck to our core principals of keeping it simple and using Blockchain for what it is really good at, in this case the access control, encryption and decryption of private medical data. Our stress tests show a really scalable implementation and the founding blocks of the project are all based on mature foundations and technologies. We are looking forward to the public launch of the mobile application and are enjoying using all our Blockchain experience to build what we hope will be a battle-ready scalable Blockchain experience leading the way for web applications in the future and demonstrating a really relevant and exciting use of Blockchain in decentralized PKI.

COVID-19 Blockchain response ->

In these difficult times we’ve published a POC system for a blockchain distributed system to provide data feeds and implement a traffic light system, follow the blogs here: https://medium.com/@ed_burton/a-blockchain-covid-response-system-poc-889d9b74786e

--

--